文本数据在Python3中由str对象处理。str为不可改变序列,由Unicode编码构成,可通过 str.join() 或 io.StringIO 来高效操作需要由多个片段构成的字符串。
1. 字符串构建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
>>> # 使用字面量构建字符串对象 >>> str1= 'single quote' >>> str2= "double quote" >>> str3= '''single ... quote ... multilines''' >>> str4= """double ... quote ... multilines""" >>> print(str1, str2, str3, str4, sep='\n') single quote double quote single quote multilines double quote multilines >>> >>> # 使用构造函数构建字符串 >>> str5= str(123) >>> str6= str(1.23) >>> str7= str(object()) >>> print(str5, str6, str7, sep='\n') 123 1.23 <object object at 0x101666290> >>> |
2. 字符串拼接
字符串的拼接通常有如下三种方法:
1 2 3 4 5 6 7 8 9 10 11 |
# 1. 字面量拼接:要求所有待拼接的字符串均为字面量,不能有变量,字面量之间用空格隔开。 str1= "abc" "def" "gh" print(str1) # abcdefgh # 2. 通过‘+’连接:当只有少量字符串对象需要连接时推荐使用该方法 str2= str1 + '123' print(str2) # abcdefgh123 # 3. 通过‘join()’函数连接:当有大量字符串序列需要链接时推荐使用 str3= ','.join(['aa', 'bb', 'cc', 'dd']) print(str3) # aa,bb,cc,dd |
3. 字符串分割
可通过 split(sep=None, maxsplit=-1) 函数将字符串分割为若干子字符串:
1 2 3 4 5 |
str1 = "a*b * c*d" str1.split() # ['a*b', '*', 'c*d'] str1.split('*') # ['a', 'b ', ' c', 'd'] str1.split(sep='*') # ['a', 'b ', ' c', 'd'] str1.split(sep='*', maxsplit=1) # ['a', 'b * c*d'] |
4. 字符串截取
可通过集合的分片方法截取字符串中的指定子串:
1 2 3 4 5 6 7 8 9 10 11 12 |
""" 分片截取规则 语法: sequence[start:stop:step] sequence:用于分片操作的序列对象 start:分片开始索引位置,默认值为0(即字符串开始位置) stop:分片结束索引位置,默认值为-1(即字符串结束位置) step:分片的步长,默认值为1 返回值:序列sequence中从start开始,按照步长step递增,直到stop位置为止的所有元素构成的子集合 """ str2="Hello, Python!" print(str2[0:5]) # Hello print(str2[-7:-1]) # Python print(str2[1:-1:2]) # el,Pto |
5. 字符串查找替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
""" 字符串查找 str.find(sub[, start[, end]]) sub: 待查找的子字符串 start:查找开始位置索引 end:查找结束位置索引 返回值:待查找的子字符串首次出现的索引值;若未查找到,返回-1 """ 'abcd-abcd'.find('bc') # 1 'abcd-abcd'.find('bc', 4) # 6 """ 字符串替换 str.replace(old, new[, count]) old:待替换的字符串 new:替换为的字符串 count:替换次数 返回值:替换后的整个字符串 """ 'abcd-abcd'.replace('bc','BC') # 'aBCd-aBCd' 'abcd-abcd'.replace('bc','BC', 1) # 'aBCd-abcd' |
6. 消除字符串首尾特定字符
1 2 3 4 5 6 7 8 9 10 11 12 13 |
""" str.strip([chars]) # 消除字符串首尾两侧的特定字符 str.lstrip([chars]) # 消除字符串左侧特定字符 str.rstrip([chars]) # 消除字符串右侧特定字符 chars:需要消除的字符序列 返回值:消除特定字符后的子字符串 """ ' Hello, Python! '.strip() # 'Hello, Python!' ' Hello, Python! '.lstrip() # 'Hello, Python! ' ' Hello, Python! '.rstrip() # ' Hello, Python!' '* xHello, Python! *'.strip(' *') # 'xHello, Python!' '* xHello, Python! *'.lstrip(' *') # 'xHello, Python! *' '* xHello, Python! *'.rstrip(' *') # '* xHello, Python!' |
7. 字符串对齐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
""" str.center(width[, fillchar]) # 将字符串剧中对齐,并使用填充字符填充其左右 str.ljust(width[, fillchar]) # 将字符串剧左对齐,并使用填充字符串填充其右侧 str.rjust(width[, fillchar]) # 将字符串剧右对齐,并使用填充字符串填充其左侧 width:填充后的总宽度 fillchar:填充字符 返回值:填充后的字符串 """ 'Hello, Python!'.center(30) # ' Hello, Python! ' 'Hello, Python!'.center(30, '*')# '********Hello, Python!********' 'Hello, Python!'.ljust(30) # 'Hello, Python! ' 'Hello, Python!'.ljust(30, '*') # 'Hello, Python!****************' 'Hello, Python!'.rjust(30) # ' Hello, Python!' 'Hello, Python!'.rjust(30, '*') # '****************Hello, Python!' |
8. 字符串格式化
Python3中字符串的格式化可以使用%操作符或str.format函数进行,相比前者str.format函数格式化更为精简和准确,也更容易学习和使用。以下为其格式化语法说明:
1 2 3 4 5 6 7 8 |
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type] fill ::= <any character> align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= digit+ grouping_option ::= "_" | "," precision ::= digit+ type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" |
具体的参数解释可参考官方文档。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# 1. 使用位置参数 'Name: {}, Age: {}'.format('jack', 19) # 'Name: jack, Age: 19' 'Name: {0}, Age: {1}'.format('jack', 19) # 'Name: jack, Age: 19' 'Age: {1}, Name: {0}'.format('jack', 19) # 'Age: 19, Name: jack' # 2. 使用关键字参数 'Name: {name}, Age: {age}'.format(name='jack', age=19) # 'Name: jack, Age: 19' 'Name: {name}, Age: {age}'.format(**{'name':'jack', 'age':19}) # 'Name: jack, Age: 19' # 3. 数据格式化 'PI={}'.format(3.1415927) # 'PI=3.1415927' 'PI={0:.5f}'.format(3.1415927) # 'PI=3.14159' 'PI={0:30.5f}'.format(3.1415927) # 'PI= 3.14159' 'PI={0:^ 30.5f}'.format(3.1415927) # 'PI= 3.14159 ' 'PI={0:*^ 30.5f}'.format(3.1415927) # 'PI=*********** 3.14159***********' 'PI={0:*^+30.5f}'.format(3.1415927) # 'PI=***********+3.14159***********' 'PI={0:*^+30.5f}'.format(-3.1415927) # 'PI=***********-3.14159***********' |
9. 字符串编码解码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
""" 字符串编码 str.encode(encoding="utf-8", errors="strict") encoding:编码类型 errors:当编码发生错误时的处理方式:'strict'触发UnicodeError异常;'ignore':忽略;'replace':使用预定义字符替换出错字符。。。 返回值:编码后的字节数组 """ 'abc我的edf'.encode() # b'abc\xe6\x88\x91\xe7\x9a\x84edf' 'abc我的edf'.encode(encoding='ascii', errors="replace") # b'abc??edf' """ 字符串解码 bytes.decode(encoding="utf-8", errors="strict") encoding:解码类型 errors:当解码发生错误时的处理方式:'strict'触发UnicodeError异常;'ignore':忽略;'replace':使用预定义字符替换出错字符。。。 返回值:解码后的字符串 """ b'abc\xe6\x88\x91\xe7\x9a\x84edf'.decode() # 'abc我的edf' |
10. str常用函数列表
方法名称 | 说明 |
capitalize() | 返回一个首字母大写的字符串副本 |
casefold() | 将大写字母转换为小写,大多数时候同lower(),但针对特定国际化语言更通用 |
center(width[, fillchar]) | 使用填充字符使字符串居中 |
count(sub[, start[, end]]) | 计算字符串中sub出现的次数 |
encode(encoding=”utf-8”, errors=”strict”) | 编码字符串 |
startswith(prefix[, start[, end]]) | 字符串是否以prefix开头 |
endswith(suffix[, start[, end]]) | 字符串是否以suffix结尾 |
expandtabs(tabsize=8) | 将字符串中的tab字符替换为指定数量的空格 |
find(sub[, start[, end]]) | 查找字符串sub |
index(str, beg=0, end=len(string)) | 跟find()方法一样,只不过如果str不在字符串中会报一个异常。 |
format(args, *kwargs) | 格式化字符串 |
index(sub[, start[, end]]) | 返回子串sub的索引位置 |
join(iterable) | 连接字符串 |
ljust(width[, fillchar]) | 使用填充字符使字符串向左对齐 |
rjust(width[, fillchar]) | 使用填充字符使字符串向右对齐 |
lower() | 字符串转小写 |
strip([chars]) | 删除字符串开头和结尾的指定字符或空白 |
lstrip([chars]) | 删除字符串开头的指定字符或空白 |
rstrip([chars]) | 删除字符串结尾的指定字符或空白 |
partition(sep) | 将字符串从sep子串第一次出现的地方,将其分为三部分,返回一个元组(seq之前部分,seq,seq之后部分) |
replace(old, new[, count]) | 使用new替换字符串中所有old |
split(sep=None, maxsplit=-1) | 分隔字符串 |
splitlines([keepends]) | 分隔多行文本,keepends为真时保留换行符 |