目录
本章将会介字符串格式化其他的值(如打印特殊格式的字符串),并简单了解下利用字符串的分割、连接、搜索等方法能做些什么。
3.1 基本的字符串
所有标准的序列操作(索引、分片、判断成员资格、求长度、取最小值和最大值)对字符串同样适用,上一章已经讲过了这些操作。但是,请记住字符串都是不可变的。因此,如下所示的项或分片赋值都是不合法的。
>>> website = 'http://www.python.org'
>>> website[-3:] = 'com'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
3.2 格式化字符串:精简版
字符串格式化使用字符串格式化操作符,即百分号%来实现。
Ps:%也可以用作模运算(求余)操作符。
在%的左侧放置一个字符串(即格式化字符串),而右侧则放置希望被格式化的值,可以使用一个值,如一个字符串或者数字,也可以使用多个值的元组或者下一章将会讨论的字典(如果希望格式化多个值的话)。
>>> format = "Hello, %s, %s enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world, Hot enough for ya?
值和格式化字符串数要对应
>>> format = "Hello, %s, %s enough for ya?"
>>> values = ('world')
>>> print format % values #一个值不够
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> values = ('world','sss','sada')
>>> print format % values #三个值多了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> print format % values[0:2] #利用分片筛选2个值通过
Hello, world, sss enough for ya?
Ps:如果使用列表或者其他序列代替元组,那么序列会被解释为一个值。只有元组和字典(第四章)可以格式化一个以上的值。
>>> format = "Hello, %s, %s enough for ya?"
>>> values = ['world', 'Hot']
>>> print format % values #使用列表,显示参数值不够
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
#需要写入两个值
>>> format = "Hello, %s, %s enough for ya?"
>>> value1 = ['world']
>>> value2 = ['Hot']
>>> print format % (value1,value2)
Hello, ['world'], ['Hot'] enough for ya? #打印的结果有列表符号
>>> print format % (value1[0],value2[0])
Hello, world, Hot enough for ya?
格式化字符串的%s部分称为转换说明符(conversion specifier),它们标记了需要插入转换值的位置。 s表示值会被格式化为字符串---如果不是字符串,则会用str将其转换为字符串、这个方法对大多数值都有效。其他转换说明符见本章后面的表3-1。
Ps:如果要在格式化字符串里面包括百分号,那么必须使用%%,这样python就不会把%误认为是转换说明符了。
>>> print " Until now, you have already completed the %.1f %%!" % (98.123)
Until now, you have already completed the 98.1 %!
如果要格式化实数(浮点数),可以使用f说明转换说明符的类型,同时提供所需要的精度:一个句点再加上希望保留的小数位数。因为格式化转换说明符总是以表示类型的字符结束,所以精度应该放在类型字符前面:
>>> format = "Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142
模板字符串
String模块提供另外一种格式化值的方法:模板字符串。他的工作方式类似于很多unix shell里的变量替换。如下substitute这个模板方法会用传递进来的关键字参数foo替换字符串中的$foo(有关关键字参数的详细信息,看第6章)
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而准确指明结尾:
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
可以使用$$插入美元符号,类似于%%
>>> s = Template("Make $$ selling $x!")
>>> s.substitute(x='slurm')
'Make $ selling slurm!'
除了关键字参数之外,还可以使用字典变量提供值/名称对(第四章)。
>>> s = Template("A $thing must never $action.")
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
>>> print d #打印下d,提前熟悉一下
{'action': 'show his socks', 'thing': 'gentelman'}
方法safe_substitute不会因为缺少值或者不正确使用$字符而出错。
>>> s = Template("Make $$ selling $x!")
>>> s.substitute() #没有参数会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
File "/usr/lib64/python2.7/string.py", line 162, in convert
val = mapping[named]
KeyError: 'x'
>>> s.safe_substitute() #使用safe_substitute()不会报错
'Make $ selling $x!'