首页 > 编程语言 > 详细

Python 字符串

时间:2019-04-16 15:42:14      阅读:124      评论:0      收藏:0      [点我收藏+]

本文主要总结字符串的知识点。

一、字符串格式化

字符串格式化使用百分号%来实现。

#字符串格式化一个值
hellosta = "hello,%s"
str = "susan"
print(hellosta % str)  #hello,susan

hellotwo = "hello,%s and %s"
names = ("su","jane")
names2 = ["su","jame"]
#只有元组和字典可以格式化一个以上的值
print(hellotwo % names) #hello,su and jane
print(hellotwo % names2) #TypeError: not enough arguments for format string

基本的转换说明符包括以下部分:

(1)%字符:标记转换说明符的开始。

(2)转换标志(可选):- 表示左对齐;+ 表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充。

(3)最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度从值元组中读出;

(4)点(.)后跟精度值(可选):如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出。

(5)转换类型:

技术分享图片

例子:

#精度为2
p = %.2f%pi
print(p)  #3.14
#宽度为5
p2 = %.5s%hello,world
print(p2) #hello
#也可以用*表示精度和宽度
p3 = %.*s%(5,hello,world)
print(p3) #hello

也可以使用模板字符串格式化--这个可以查看(Python 自动生成代码 方法二 )这篇文章。

 二、字符串方法

1、查找子串

find方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到则返回-1.

str = "hello,world.It started"
substr = world
print(str.find(substr)) #6
nostr = su
print(str.find(nostr)) #-1

2、大小写

str1 = "Hello,World.That`s All"
str2 = "hello,world.that`s all"
#小写
print(str1.lower()) #hello,world.that`s all
#大写
print(str2.upper()) #HELLO,WORLD.THAT`S ALL
#单词首字母大写,有点瑕疵
print(str2.title()) #Hello,World.That`S All
print(string.capwords(str2)) #Hello,world.that`s All

3、替换字符\字符串

replace方法返回某字符串的所有匹配项均被替换之后得到字符串。

translate方法可以替换字符串中的某些部分,和replace方法不同的是,它只处理单个字符。

restr = "this is a cat.cat is lovely"
#restr.replace(old, new, count),count表示最多可以替换多少个字符串
print(restr.replace(cat, dog, 1)) #this is a dog.cat is lovely
#translate(table)
table = str.maketrans(it,ad)
print(restr.translate(table)) #dhas as a cad.cad as lovely

4、连接\分割\除空格

join方法用来连接序列中的元素;

split方法用来将字符串分割成序列;

strip方法返回去除两侧(不包括内部)空格的字符串;

seq = [a,2,c,d]
sep = +
joinstr = sep.join(seq)
print(joinstr) #a+2+c+d
splitstr = joinstr.split(+)
print(splitstr) #[‘a‘, ‘2‘, ‘c‘, ‘d‘]
stripstr = "        !!hello world !! **   "
print(stripstr.strip()) #!!hello world !! **
print(stripstr.strip( *!)) #hello world

 

Python 字符串

原文:https://www.cnblogs.com/susan-su/p/10716962.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!