字符串基本操作
>>> website = 'http://www.python.org'
>>> website[-3:] = 'com'
TypeError: object doesn't support slice assignment
设置字符串的格式
替换字段组成:替换字段由字段名、转换标志、格式说明符组成。
字段名:索引、标识符。指出要设置哪个值的格式并使用结果来替换该字段。除指定值外,还可指定值的特定部分,如列表的元素。
转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(repr),s(str)和a(ascii)。如果你指定了转换标志,将不使用对象本身的格式来设置机制,而是使用指定的函数将对象转换为字符串,再做进一步的格式设置。
格式说明符:跟在冒号后面的表达式。能详细的指定最终的格式,包括格式类型(字符串、浮点数或十六进制数)、字段宽度和数的精度,如何显示符号和千位分隔符,以及对齐和填充的方式。
替换字段名
向format提供要设置其格式的未命名参数,并在格式字符串中使用未命名字段(此时将按顺序将字段和参数配对),还可给参数指定名称(被用于相应的替换字段中)
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
'3 1 4 2'
#并非只能使用提供的值本身,可访问其组成部分
#可以使用索引
>>> fullname = ["Alfred", "Smoketoomuch"]
>>> "Mr {name[1]}".format(name=fullname)
'Mr Smoketoomuch'
【???P44】
#可使用句点表示法来访问导入的模块中的方法、属性、变量和函数
#变量_name_包含指定模块的名称
>>> 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 π
基本转换
指定要在字段中包含的值后,就可添加如何设置其格式的指令。首先可提供一个转换标志
#转换标志(s、r、a)指定分别使用str、repr和ascii进行转换。
#函数str通常创建外观普通的字符串版本;
#函数repr尝试创建给定值的python表示;
#函数ascii创建只包含ASCII字符的表示;
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
#还可指定要转换的值是哪种类型
#如提供一个整数,但将其作为小数进行处理,可格式说明符(冒号后面)使用字符f
>>> "The number is {num}".format(num=42)
'The number is 42'
>>> "The number is {num:f}".format(num=42)
'The number is 42.000000'
#也可将其作为二进制数处理
>>> "The number is {num:b}".format(num=42)
'The number is 101010'
宽度、精度和千位分隔符
设置浮点数或其他更具体的小数类型时,默认在小数点后面显示六位小数。根据需求有时需要在格式说明中指定宽度和精度。
#宽度是使用整数指定的
#数和字符串的对齐方式不一样
>>> "{num:10}".format(num=3)
' 3'
>>> "{name:10}".format(name="Bob")
'Bob '
#精度是使用整数指定的
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'
#可同时指定宽度和精度
>>> "{pi:10.2f}".format(pi=pi)
' 3.14'
#可使用逗号来指出要添加千位分隔符
>>> 'One googol is {:,}'.format(10**100)
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,00
0,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
#同时指定其他格式设置元素时,逗号应放在宽度和精度之间
符号、对齐和用0填充
在指定宽度和精度的数前面,可以添加一个标志(0、+、-、空格),0表示使0来填充数字
>>> '{:010.2f}'.format(pi)
'0000003.14'
#指定左对齐、右对齐和居中,可分别使用<、>和^
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
3.14
3.14
#可以使用填充字符来扩充对齐说明符
>>> "{:$^15}".format(" WIN BIG ")
'$$$ WIN BIG $$$'
#更具体的说明符=,将填充字符(空格)放在符号和数字之间
>>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
3.14
-3.14
>>> print('{0:10.2f}\n{1:=10.2f}'.format(pi, -pi))
3.14
- 3.14
#要给正数加上符号,可使用说明符+(将其放在对齐说明符),而不是默认的-
>>> print('{0:-.2}\n{1:-.2}'.format(pi, -pi)) #默认设置
3.1
-3.1
>>> print('{0:+.2}\n{1:+.2}'.format(pi, -pi))
+3.1
-3.1
#如果将符号说明符指定为空格,会在正数前面加上空格而不是+
>>> print('{0: .2}\n{1: .2}'.format(pi, -pi))
3.1
-3.1
#井号(#)选项,将其放在符号说明符和宽度之间(如果指定了这两种设置),转换细节岁类型而异
#对于二进制、八进制和十六进制转换,会加上一个前缀
>>> "{:b}".format(42)
'101010'
>>> "{:#b}".format(42)
'0b101010'
#对于各种十进制数,要求必须包含小数点(对于类型g,它保留小数点后面的0)
>>> "{:g}".format(42)
'42'
>>> "{:#g}".format(42)
'42.0000'
字符格式例子【???p47】
#根据指定的宽度打印格式良好的价格列表
width = int(input('Please enter width: '))
price_width = 10
item_width = width - price_width
header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)
print('=' * width)
print(header_fmt.format('Item', 'Price'))
print('-' * width)
print(fmt.format('Apples', 0.4))
print(fmt.format('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))
print('=' * width)
这个程序的运行情况类似于下面这样:
Please enter width: 35
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs.) 12.00
===================================
字符串方法
1.center
方法center通过在两边添加填充字符(默认为空格)让字符串居中。
>>> "The Middle by Jimmy Eat World".center(39)
' The Middle by Jimmy Eat World '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'
2.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('Python')
6
>>> title.find('Flying')
15
>>> title.find('Zirquss')
-1
#还可以用与类似垃圾邮件过滤检查主题是否包含'$$$'
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
#可指定搜索的起点和终点
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # 只指定了起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1
3.join
用于合并序列的元素
#所合并序列的元素必须都是字符串
>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
TypeError: sequence item 0: expected string, int found
#尝试合并一个数字列表
#合并一个字符串列表(注意合并之后的内容)
>>> seq = ['1', '2', '3', '4', '5']
>>> sep='+'
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
4.lower
方法lower返回字符串的小写版本
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
#将所有单词转为小写,有利于搜索
>>> name = 'Gumby'
>>> names = ['gumby', 'smith', 'jones']
>>> if name.lower() in names: print('Found it!')
Found it!
#一个与lower相关的方法是title,它将字符串转换为词首大写
#即所有单词的首字母都大写,其他字母都小写(确定单词边界的方式可能导致结果不合理)
>>> "that's all folks".title()
"That'S All, Folks"
#使用模块string中的函数capwords
>>> import string
>>> string.capwords("that's all, folks")
That's All, Folks"
5.replace
方法replace将指定子串都替换为另一个字符串,并返回替换后的结果
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
6.split
用于将字符串拆分为序列
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']
#注意,如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分
7.strip
方法strip将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
#去掉不必要的空格,有利于搜索
>>> names = ['gumby', 'smith', 'jones']
>>> name = 'gumby '
>>> if name.strip() in names: print('Found it!')
Found it!
#【???p51】
####如果又要小写,又要删除空格,然后再搜索怎样做
#还可在一个字符串参数中指定要删除哪些字符
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'
#这个方法只删除开头或末尾的指定字符,因此中间的星号未被删除
8.translate
方法translate与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。 这个方法的优势在于能够同时替换多个字符,因此效率比replace高;
使用translate前必须创建一个转换表(这个转换表指出了不同Unicode码点之间的转换关系),要创建转换表,可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符
#转换表
>>> table = str.maketrans('cs', 'kz')
#创建转换表后,就可将其用作方法translate的参数
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
#调用方法maketrans时,还可提供可选的第三个参数,指定要将哪些字母删除
>>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt'
9.判断字符串是否满足特定的条件【???p52】
很多字符串方法都以is打头,如isspace、isdigit和isupper,它们判断字符串是否具有特定的性质(如包含的字符全为空白、数字或大写)。如果字符串具备特定的性质,这些方法就返回True,否则返回False
新函数
函数 | 功能 |
string.capwords(s[, sep])
|
使用
split
根据
sep
拆分
s
,将每项的首字母大写,再以空格为分隔符将它们合并起来
|
ascii(obj)
|
创建指定对象的
ASCII
表示
|