目录
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 设置字符串格式:精简版
将值转换为字符串并设置其格式是一个重要的操作,Python提供了多种字符串格式设置方法。
主要的解决方案是使用字符串格式设置运算符——百分号。
>>> format="Hello,%s. %s enough for ya?"
>>> values=('World','Hot')
>>> format%values
'Hello,World. Hot enough for ya?'
上述格式字符串中的%s称为转换说明符,指出了要将值插入什么地方。s意味着将值视为字符串进行格式设置。如果指定的值不是字符串,将使用str将其转换为字符串。
其他说明符将导致其他形式的转换。例如,%.3f将值的格式设置为包含3位小数的浮点数。
>>> Num="Value is %.3f"
>>> value=3
>>> Num%value
'Value is 3.000'
包含等号的参数称为关键字参数,在字符串格式设置中,可将关键字参数视为一种向命名替换字段提供值的方式。
>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for ya?")
>>> tmpl.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'
编写新代码时,应选择使用字符串方法format,每个替换字段都用花括号括起,其中可能包含名称,还可能包含有关如何对相应的值进行转换和格式设置的信息。
>>> Str1="{},{} and {}"
>>> Str1.format("first","second","third")
'first,second and third'
>>> "{0},{1} and {2}".format("first","second","third")
'first,second and third'
>>> "{0} {1} {2} {3} {0} {1} {4} {5} {6} {7}".format('TO','Be','Or','Not','That','Is','The','Question')
'TO Be Or Not TO Be That Is The Question'
格式说明符.2f,并使用冒号将其与字段名隔开。它意味着要使用包含2位小数的浮点数格式。如果没有指定.2f。
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'
>>> "{name} is approximately {value}.".format(value=pi, name="π")
'π is approximately 3.141592653589793.'
3.3 设置字符串格式:完整版
字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。
转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(表示repr)、s(表示str)和a(表示ascii)。
格式说明符:跟在冒号后面的表达式(这种表达式是使用微型格式指定语言表示的)。格式说明符让我们能够详细地指定最终的格式,包括格式类型(如字符串、浮点数或十六进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
3.3.1 替换字段名
向format提供要设置其格式的未命名参数,并在格式字符串中使用未命名字段。
>>> "{foo} {} {bar} {}".format(1,2,bar=4,foo=3)
'3 1 4 2'
>>>
>>>
>>> "{foo} {1} {bar} {0}".format(1,2,bar=4,foo=3)
'3 2 4 1'
>>> String=["Tony"," smoke too much"]
>>> "Mr {name[1]}".format(name=String)
'Mr smoke too much'
>>> import math
>>> tmpl = "The {mod.__name__} module defines the value {mod.pi} for π"
>>> tmpl.format(mod=math)
'The math module defines the value 3.141592653589793 for π'