1.基本字符串操作

所有标准序列的操作对字符串同样适用,上一张已经讲述了这些操作。一定要记住,字符串是不可变的。       

字符串的格式化参考

1.1传统C语言式


title = list('hello')
name = 'world'
print  ("%s,%s"% (title,name))



['h', 'e', 'l', 'l', 'o'],world



1.2命名参数

title = "world"
year = 2013
print ("hello %(titles)s, %(years)10d" % {"titles":title, "years":year})



hello world, 2013



"hello {title}, {year}".format(title=title, year=year)
"hello {title}, {year}".format(**{"title":title, "year":year})


'hello world, 2013'



#string.format 也支持命名参数
string.format还有一个地方需要注意,如果参数是unicode,则string也必须是unicode,否则,会触发异常:


title = u"标题党"
"hello {0}".format(title)
'hello 标题党'
#

1.3位置参数




import datetime

title = "world"
year = 2013
print ("hello {0}, {1}".format(title, year))


print ("today is {0:%Y-%m-%d}".format(datetime.datetime.now()))
hello world, 2013
today is 2017-11-13#datetime参考此处
1.4字符串格式:%[(name)][flag][width][.][precision]type
    
    
     
     name:可为空,数字(占位),命名(传递参数名,不能以数字开头)以字典格式映射格式化,其为键名
     
     flag:标记格式限定符号,包含+-#和0,+表示右对齐(会显示正负号),-左对齐,前面默认为填充空格(即默认右对齐),0表示填充0,#表示八进制时前面补充0,16进制数填充0x,二进制填充0b
     
     width:宽度(最短长度,包含小数点,小于width时会填充)
     
     precision:小数点后的位数,与C相同
     
     type:输入格式类型,看下表
     
     
     
     %% 百分号标记
     
     %c 字符及其ASCII码
     
     %s 字符串
     
     %d 有符号整数(十进制)
     
     %u 无符号整数(十进制)
     
     %o 无符号整数(八进制)
     
     %x 无符号整数(十六进制)
     
     %X 无符号整数(十六进制大写字符)
     
     %e 浮点数字(科学计数法)
     
     %E 浮点数字(科学计数法,用E代替e)
     
     %f 浮点数字(用小数点符号)
     
     %g 浮点数字(根据值的大小采用%e或%f)
     
     %G 浮点数字(类似于%g)
     
     %p 指针(用十六进制打印值的内存地址)
     
     %n 存储输出字符的数量放进参数列表的下一个变量中


1.5模板字符串

string模块提供另外一种格式化的方法:

from string import Template
s = Template('$x,glorious $x!')  #如果替换单词的一部分,那么x需要用花括号括起来 s=Template(make $$ selling ${x} again)
s.substitute(x='slurm')           # $$ 插入$符号
'slurm,glorious slurm!'

s =Template('A $thing must never $action')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his socks'
print (s.substitute(d))
print (d)
-find
find方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到就返回-1。这个方法还可以接受可选的起始点和结束点参数:

subject = 'wei suo yu wei'
print (subject.find('wei'))
print (subject.find('wei',1))
dirs = ['wang','luo','dan']
'/'.join(dirs)
a = '** dian deng  * '   #最后是一个空格
a.strip('*')

-replace
与replace相似,不过translate只处理单个字符。在使用translate转换之前,需要先完成一张转换表,有点复杂,可以直接使用string模块里的maketrans。maketrans函数接受两个等长的参数(在python3中maketrans已经变成内建函数maketrans),表示第一个字符串中的每个字符都用第二个字符串中的相同位置的字符替换:
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))
# 制作翻译表
bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
# 转换为大写,并删除字母o
print(b'runoob'.translate(bytes_tabtrans, b'o'))