第三章 使用字符串
1 字符串基本操作 (字符串是不可变的)
索引 分片 乘法 判断成员资格 求长度 取最小值和最大值
2 字符串格式化(精简)
示例代码如下:
>>> format="hello %s %senough for ya?"
>>> values=('world','hot')
>>> print(format % values)
hello world hot enough for ya?
%s为转换说明符,如果格式化字符串中包含百分号要用%%代替
格式化实数,示例代码如下:
>>> format="Pi with threedecimals: %.3f"
>>> from math import pi
>>> 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'
如果替换变量是单词的一部分,标例代码如下:
>>> s=Template("It is${x}tastic!")
>>> s.substitute(x='slurm')
'It is slurmtastic!'
也可以使用字典变量来进行替换,示例代码如下:
>>> s=Template('A $thing mustnever $action')
>>> d={}
>>> d['thing']='gent leman'
>>> d['action']='show his socks'
>>> s.substitute(d)
'A gent leman must never show his socks'
注:如果替换字符中含有$符号,要用$$进行替换
3 字符串格式化(完整),这个有点像c 中格式化标识符
格式化操作符的右操作数可以是任何东西,如果右侧是元组,则其中的每一个元素都会被单独格式化
字符串格式化转换类型
d.i 带符号的十进制
o 不带符号的八进制
u 不带符号的十进制
x 不带符号的十六进制(小写)
X 不带符号的十六进制(大写)
e 科学计数法的浮点数(小写)
E 科学计数法的浮点数(大写)
f,F 十进制浮点数
g 如果指数大于-4或小于精度值则和e相同,其他情况与f相同
G 如果指数大于-4或小于精度值则和E相同,其他情况与F相同
C 单字符
r 字符串
s 字符串
简单转换 示例代码如下:
>>>"price of eggs:$%d "% 42
'price of eggs:$42 '
>>>"hexadecimal price ofeggs: %x" % 42
'hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'pi: %f ....' %pi
'pi: 3.141593 ....'
>>>"very inexact estimatte ofpi: %i" %pi
'very inexact estimatte of pi: 3'
>>>"using str: %s " %42
'using str: 42 '
>>>"using repr: %r " %42
'using repr: 42 '
字段宽度和精度
>>> '%10f' %pi
' 3.141593'
>>> '%10.2f' % pi
' 3.14'
>>> '%.2f ' %pi
'3.14 '
>>> '%.5s' % 'Guido van Rossum'
'Guido'
符号 对齐和0填充
>>> '%010.2f' %pi
'0000003.14'
-表示左对齐
>>> '%-10.2f' %pi
'3.14 '
加空格可以实现对齐的效果
>>> print(('% 5d' %10)+' '+('%5d' %-10))
10
-10
+表示不管正负数都会输出符号
>>> print(('%+5d'%10)+' '+('%+5d' %-10))
+10
-10
4 字符串方法
常用的字符串常量
String.digits 包含0-9字符串
String.letters 包含所有字母
String.lowercase 包含所有小写字母的字符串
String.printable 包含所有打印字符的字符串
String.punctuation 包含所有标点的字符串
String.uppercase 包含所有大写字线的字符串
Find 在一个较长的字符串中查找子字串
>>> 'with a moo-moo here,andmoo-moo three'.find('moo')
7
Join 是split方法的逆方法
>>>seq=['1','2','3','4','5']
>>>seq.join(seq)
Traceback (mostrecent call last):
File "<pyshell#50>", line 1,in <module>
seq.join(seq)
AttributeError: 'list'object has no attribute 'join'
>>>sep='+'
>>>sep.join(seq)
'1+2+3+4+5'
Lower返回字符串的小写字母版
Replace 返加替换所有匹配字符串后的字符串
Split 是join方法的逆方法,将字符串分割成序列
Strip 去掉两侧空格
Translate 替换字符串中的某些部分,与replace不同的是只处理单个字符串