3.1基本字符串操作
通用的序列操作都可以使用。
3.2字符串的格式化
1、%:字符串格式操作符(%也是模运算符)
说明 : %的左边放置一个格式化字符串,右边放置希望被格式化的值(这个值可以是一个字符串,数字。可以使用多个值的元组或字典)
>>> format="Hello,%s,%s,enough for ya?"
>>> values=('World',"Hot")
>>> print format % values
Hello,World,Hot,enough for ya?
分析:%s部分 称为转换说明符,作用是标记需要插入转换值的位置,s表示值会被格式化成字符串,如果不是字符串,则会用str将其转换为字符串。
补充:如果要格式化浮点数,可以使用f说明转换说明符的类型,同时提供所需要的精度(格式为一个句点再加上需要保留的小数位数)。
如果需要在格式化只符串中出现%,则需要使用%%。
>>> format="PI with three decimals : %.3f"
>>> from math import pi
>>> print pi
3.14159265359
>>> print format % pi
PI with three decimals : 3.142
>>>
模版字符串——格式化值的另一个方法
>>> from string import Template
>>> s = Template("$x,glorious $x!")
>>> s.substitute(x='slurm')
'slurm,glorious slurm!'
>>
分析:substitute这个模版方法会用传递进来的关键字参数foo替换字符串中的$foo’
(1)如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而准确指明结尾
>>> from string import Template
>>> s = Template("It's ${x}tastic")
>>> s.substitute(x='slurm')
"It's slurmtastic"
(2)可以使用$$插入美元符号
>>> from string import Template
>>> s = Template("Make $$ selling $x!")
>>> s.substitute(x="slurm")
'Make $ selling slurm!'
(3)除了关键字参数之外,还可以使用字典变量提供值/名称对
>>> from string import Template
>>> s = Template("A $thing must never $action")
>>> d = {}
>>> d[“thing”] = “gentleman”
File "<stdin>", line 1
d[“thing”] = “gentleman”
^
SyntaxError: invalid syntax
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks'
>>>
3.3字符串格式化:完整版
1、格式化操作符%右边的操作数可以是任意类型
2、如果右操作数是元组的话,则其中的每一个元素都会被单独格式化,每个值都需要一个对应的转换说明符(必须一一对应,多一个少一个都不行)
>>> "%s plus %s equals %s" % (1,1,2)
'1 plus 1 equals 2'
>>> "%s plus %s equals %s" % (1,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s plus %s equals %s" % ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s plus %s equals %s" % (1,1,1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>
#如果右操作数是多个,那么必须将它们用圆括号括起来
>>> "%s plus %s equals %s" % 1,1,2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>>
基本转换说明符
这些项的顺序至关重要,
(1)%字符:标记转换说明符的开始
(2)转换标志(可选):-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示整数之前保留空格;0 表示转换 值若位数不够则用 0 填充
(3)最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出
(4)点(.)后跟精度值(可选);如果转换的是实数,精度就表示出现在小数点后的位数,如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出
(5)转换类型
3.3.1简单转换
>>> 'Price of eggs: $%d' % 42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs :$%x' % 42
'Hexadecimal price of eggs :$2a'
>>> from math import pi
>>> 'PI is :%f' % pi
'PI is :3.141593'
>>>
3.3.2字段宽度和精度
>>> from math import pi
>>> '%.2f' % pi
'3.14'
>>>
>>> '%10f' % pi
' 3.141593'
>>> '%010f' % pi
'003.141593'
>>> '%10.2f' % pi
' 3.14'
>>> '%-10.2f' % pi
'3.14 '
>>> '%+10.2f' % pi
' +3.14'
#
>>> '%.5s' % "Guido van Rossum"
'Guido'
>>>
3.3.3符号,对齐,和用0填充
#用0填充没起作用,原因0只会填充小数点前面的空位
>>> '%-+010.2f' % pi
'+3.14 '
>>> '%0-+10.2f' % pi
'+3.14 '
>>> '%0+10.2f' % pi
'+000003.14'
>>> '%0-10.2f' % pi
'3.14 '
#“ ”空白意味在正数前加上空格,在需要对齐正负数是很有用
>>> print ('%d' % 10)+'\n'+('%d' % -10)
10
-10
>>> print ('% d' % 10)+'\n'+('% d' % -10)
10
-10
>>> print ('% 5d' % 10)+'\n'+('% 5d' % -10)
10
-10
#这里没有使用“”空白只是指定了字段宽度,也达到了对齐的 效果
>>> print ('%5d' % 10)+'\n'+('%5d' % -10)
10
-10
>>> print ('%+5d' % 10)+'\n'+('%+5d' % -10)
+10
-10
>>>
3.4字符串方法
3.4.1 find()
find()方法:可以在一个较长的字符串中查找子串。它返回子串所在位置的最左端的索引,如果没有找到就返回-1
>>> "With a moo-moo here, and a moo-moo there".find("moo")
7
>>> title="Monty Python's Flying Circus"
>>> title.find("Monty")
0
>>> title.find("monty")
-1
>>>
这个方法还可以接收起始点和结束点参数,查找范围包含第一个索引但是不包含第二个索引
>>> subject = '$$$ Get.rich now! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)#起始点参数
18
>>> subject.find('$$$',1,16)#起始点,结束点参数
-1
>>>
3.4.2join()
用来连接序列中的元素,但是需要被连接的元素必须是字符串
>>> seq=['1','2','3','4','5']
>>> sep='+'
>>> sep.join(seq)
'1+2+3+4+5'
3.4.3lower
返回字符串的小写字母版
>>> "Hello World".lower()
'hello world'
>>>
补充1:title():将字符串转换为标题,也就是所有单词的首字母大写,而其他字母小写
>>> 'hello world'.title()
'Hello World'
>>>
补充2:string模块的capwords()功能同title()
>>> string.capwords("that's all, folks")
"That's All, Folks"
>>> "that's all, folks".title()#显然这两种方法的,单词划分方法有区别
"That'S All, Folks"
3.4.4replace
返回某字符串的所有匹配项均被替换之后得到的字符串
>>> "This is a test".replace("is","eez")
'Theez eez a test'
>>>
3.4.5split()
它是join的逆方法,用来将字符串分隔成序列
如果不提供分隔符,程序会
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '1 2 3 4 5'.split()
['1', '2', '3', '4', '5']
>>>
3.4.6strip()
返回去除两侧空格的字符串(不包括内部字符串)
>>> " Hello World !!! ".strip()
'Hello World !!!'
>>>
可以指定需要去除的字符,将它们列为参数即可
>>> " Hello World !!! ".strip(' H')
'ello World !!!'
>>> " Hello World !!! ".strip(' H!')
'ello World'
>>>
3.4.7translate()
功能和replace方法一样,可以替换字符串中的某些部分。不同的是Translate方法只处理单个字符。它的优势在于可以同时进行多个替换,有些时候比replace效率高的多