本文几乎囊括了字符串strings的全部使用方法,便于快速学习上手,也便于在使用时查阅。
其它类型的使用方法:列表、字典、集合。
目录
- 字符串
- 字符串方法
- 大小写(capitalize(), upper(), lower(), casefold(), title())
- 索引、查找(index(), rindex(), find(), rfind())
- 统计元素个数(count())
- 判断(isX())
- 开头、结尾(startswith(), endswith())
- 删除开头、结尾(lstrip(), rstrip(), strip(), removeprefix(), removesuffix())
- 连接和分割(join(), split(), splitlines(), rsplit(), partition(), rpartition())
- 对齐(center(), ljust(), rjust())
- 替换(replace())
- 填充(zfill())
- 格式化(format(), format_map())
- 转换表(maketrans(), translate())
- 替换tab(expandtabs())
- 编码(encode())
字符串
字符串类型
在python中,字符串以单引号'
或双引号"
开头和结束,如
str1 = 'python'
str2 = "python"
但是,如果字符串内包含了单引号或者双引号呢?可有如下几种方法。
- 单双引号混用
如果字符串中有单引号'
,那么字符串用双引号"
开头和结尾;如果字符串中有双引号"
,则以单引号'
开头和结尾,如
str1 = 'hello " world'
str2 = "hello ' world"
- 转义字符
字符串中可以使用转移字符,尤其适用于字符串中既有单引号'
又有双引号"
的情况。如
str = 'hello \' world' # hello ' world
如果使用原始字符串,即在字符串开始的引号前加上r
,则会忽略所有的转移字符,认为斜杠\
是字符串的一部分,如
print(r'hello \' world') # hello \' world
- 三重引号
如果字符串跨越多行,包含换行、引号、制表符等,字符串可使用 3 个单引号或 3 个双引号作为开始或结束。如
print('''Hello
world,
'python''')
三个双引号开头和结束的内容可作为多行注释。
字符串还可以用str()
函数构造。
下标和切片
字符可使用下标或切片,来获取字符串中的字符或字符串,下标从0开始,如
s = 'Hello world!'
print(s[0]) # 输出H
print(s[6]) # 输出w
print(s[-1]) # 输出!,倒数第1个
print(s[2: 5]) # 输出lo,第2个至第5-1个
print(s[: 5]) # 输出Hello,第0个至第4个
print(s[6:]) # 输出world!,第6个至最后一个
字符串切片并非修改原来的字符,而是生成了新的字符(串)。
in
和not in
in
和not in
精确地测试(区分大小写)第 1 个字符串是否在第 2 个字符串中,输出True
或False
,如
'Hello' in 'Hello world' # True
'hello' in 'Hello world' # False
'hello' not in 'Hello world' # True
连接和倍增(+, *)
可使用加号+
连接两个字符串,如
str = 'Alice' + 'Bob' # 'AliceBob'
此方法不适用于字符串 + 整数的形式,必须显示地将数字转化为字符串。
字符串可使用*
表示倍增,如
str = 'Alice' * 5 # 'AliceAliceAliceAliceAlice'
表示有 5 个’Alice’连续地拼接起来。
*
不适用于连接 2 个字符串,或者 1 个字符串和 1 个浮点数。
长度(len())
len()
函数可以获得字符串的长度。
len('Hello') # 5
最大值、最小值(max(), min())
max()
函数获得字符串元素最大值。
max('124') # '4'
min()
函数获得字符串元素最小值。
min('abc') # 'a'
字符串方法
大小写(capitalize(), upper(), lower(), casefold(), title())
capitalize()
方法把字符串首字母变成大写。
'hello world!'.capitalize() # 'Hello world!'
upper()
方法把所有字母都转化成大写,而lower()
方法把所有字母都转化成小写。
'Hello World'.upper() # 'HELLO WORLD'
'Hello World'.lower() # 'hello world'
casefold()
能把字符串字符都转化为小写。
'HeLLo World'.casefold() # 'hello world'
casefold()
针对的字符返回更广。
swapcase()
把字符串小写转化为大写,同时把大写转化为小写。
'Hello Wrold'.swapcase() # 'hELLO wROLD'
title()
返回一个标题式的字符串,词的首字母都大写,其余字母小写。
'Hello world'.title() # 'Hello World'
该方法转换方式和机械,无法理解语言的含义。
索引、查找(index(), rindex(), find(), rfind())
index()
方法输入字符(串)可以获得它在原始字符串中首次出现的位置。如果输入的参数没有在字符串中出现过,则报错。
'abcdef'.index('b') # 1
'abcdef'.index('de') # 3
还可以传入第 2 个参数,表示查找这个参数之后第 1 次出现的位置。
'abcdefabc'.index('b', 3) # 7
还可接收第 3 个参数,表示结束位置。
rindex()
与index
类似,不过前者从字符串的最后向前搜索,而后者从字符串前向后查找。
find()
方法与index()
方法几乎类似,不同的是,如果没有找到字符(串),则返回-1,而不是报错。
rfind()
方法与find()
类似,不过前者从字符串后向前查找,而后者从字符串前向后查找。
统计元素个数(count())
count()
方法统计字符或者字串出现的次数,如
s = "I'm late! I'm late! For a very important date!"
s.count('m') # 3
s.count('ate') # 3
还可接受第 2 和第 3 个参数表示统计开始和结束的位置。
判断(isX())
除了上面讲到的isupper()
和islower()
方法外,还有其它一些以is
开头的方法,返回布尔值。
方法 | 返回True 的情况 |
---|---|
isalnum() | 字符串只包含字母和数字,并且非空,返回True |
isalpha() | 字符串只包含字母,并且非空 |
isascii() | 所有的字符都是ASCII码,或字符串为空 |
isdecimal() | 字符串只包含十进制数,并且非空 |
isdigit() | 字符串只包含数字,并且非空 |
isidentifier() | 字符串是个有效的标识符 |
islower() | 字符串只包含小写字符,并且非空 |
isnumeric() | 字符串只包含数字,并且非空 |
isprintable() | 字符串是可打印的,并且非空 |
isspace() | 字符串只包含空格、制表符和换行,并且非空 |
istitle() | 字符串仅包含以大写字母开头,后面都是小写字母的单词(可有多个单词) |
isupper() | 字符串仅包含大写字母,并且非空 |
isnumeric()
包含的编码范围比isdigit()
更广。
isX()
的写法都相同,如
'Hello world!'.islower() # False
'HELLO'.isupper() # True
'123'.isupper() # False
'HELlo'.lower().islower() # True
开头、结尾(startswith(), endswith())
若字符串有特定前缀,startswith()
返回True
;若有特定后缀,endswith()
返回True
。
'Hello world!'.startswith('Hello') # True
'Hello world!'.endswith('world!') # True
'hello world!'.startswith('abc') # False
该方法也可传入第 2 和第 3 个参数,表示起始和结束位置。
'Hello world'.endswith('wor', 3, 9) # True
这两个方法也可以传入元组,查找元组中元素有没有匹配。
'Hello world!'.startswith(('hello', 'Hello')) # True
删除开头、结尾(lstrip(), rstrip(), strip(), removeprefix(), removesuffix())
lstrip()
和rstrip()
方法分别删除开头和结尾的空白字符。
str = ' Hello world! '
print(str.lstrip()) # 'Hello world! '
print(str.rstrip()) # ' Hello world!'
这些方法还可传入参数,删除指定字符集。
str = 'abcHello world!cba'
print(str.rstrip('abcdef')) # 'abcHello world!'
这里给定的参数表示字符集合,只要开头和结尾的字符(串)的字符出现在参数的字符中,则删除。
strip()
方法是lstrip()
和rstrip()
的结合,同时对开头和结尾起作用。
lstrip()
和rstrip()
并非表示删除特定前后缀,如要删除前后缀,则要使用removeprefix()
和removesuffix()
方法。
'TestHook'.removeprefix('Test') # 'Hook'
'MiscTests'.removesuffix('Tests') # 'Misc'
如果参数并非前后缀,则返回原始字符串。
removeprefix()
和removesuffix()
为 python 3.9 新增。
连接和分割(join(), split(), splitlines(), rsplit(), partition(), rpartition())
join()
方法连接列表中的字符串,使之成为一个单独的字符串。该方法在一个字符串上调用,参数是一个字符串列表。如
', '.join(['Hello', 'world!', 'python']) # 'Hello, world!, python',逗号分隔
' '.join(['Hello', 'world!', 'python']) # 'Hello world! python', 空格分隔
split()
方法做的事情正好于join()
方法相反,它针对字符串调用,返回字符串列表。
'Hello world python'.split() # ['hello', 'world', 'python']
在默认情况下,以空白符分隔,也可传入参数,指定分隔符。
'hello,world,python'.split(',') # ['hello', 'world', 'python'],逗号做分隔。
还可以传入第 2 个参数,表示最大分割数,默认为-1。
'hello,world,python'.split(',', 1) # ['hello', 'world,python'],只分割第1个逗号。
splitliness()
更像分割句子,可以输入\n
、\r
和\r\n
等。
rstrip()
类似于split()
,不同的是,前者从最后开始分割。
partition()
输入一个分隔符,在第一次出现分隔符的地方分割字符串,返回一个三元组(分隔符前的部分,分隔符,分隔符后的部分)。
'Hello!World!ABC'.partition('!') # ('Hello', '!', 'World!ABC')
如果分隔符不存在,同样返回一个三元组(原始字符串,空字符串,空字符串)。
rpatition()
与partition()
类似,前者在最后一次出现出现分隔符的地方分割,而后者在第一次出现分隔符的地方分隔。
对齐(center(), ljust(), rjust())
center()
方法让文本居中,可输入 2 个参数,第 1 个参数表示文本总长度,第 2 个参数表示填充字符,如果省略则用空格填充。
'hello'.center(10) # ' hello '
'hello'.center(10, '&') # '&&hello&&&'
ljust()
和rjust()
用法与center()
类似,分别表示左对齐和右对齐。
'Hello'.rjust(10) # ' hello'
'Hello'.rjust(10, '*') # '*****hello'
'Hello'.ljust(10) # 'hello '
如果给定的文本长度小于字符串本身的长度,则返回原始字符串。
替换(replace())
replacce()
传入 2 个参数,第 1 个参数表示被替换的部分,第 2 个参数表示替换的部分。该方法还可以传入第 3 个参数,表示前若干次出现的为值被替换。
'HelloHelloHello'.replace('ll', 'LL') # 'HeLLoHeLLoHeLLo'
'HelloHelloHello'.replace('ll', 'LL', 1) # 'HeLLoHelloHello'
填充(zfill())
zfill()
方法用字符0
填充,输入参数表示宽度。
"42".zfill(5) # '00042'
"-42".zfill(5) # '-0042'
格式化(format(), format_map())
format()
中的参数用于替换字符串中的大括号{}
,大括号中可以包含数值所以或关键字,对应format()
中参数的位置和关键字。更详细地使用可查看字符串格式化。
"The sum of 1 + 1 is {0}".format(1+1) # 'The sum of 1 + 2 is 2'
format_map()
映射类似于字典。
class Default(dict):
def __missing__(self, key):
return key
'{name} was born in {country}'.format_map(Default(name='Guido'))
# 'Guido was born in country'
转换表(maketrans(), translate())
maketrans()
可传入 3 个参数。如果只传入 1 个参数,那必须是字典,字典的键必须是长度为 1 的字符,结果会把键转化为Unicode序号。如果传入 2 个参数,那必须是等长的字符串,返回一个字典,第 1 个字符串中的字符作为键,值是第 2 个参数对应位置的字符。如果有第 3 个参数,那必须是字符串,它的字符会被None
映射。该方法常常与translate()
配合使用。
替换tab(expandtabs())
expandtabs()
用空格替换字符串中的制表符(tab),可传入 1 个参数表示制表符的大小,默认为 8。
'01\t012\t0123\t01234'.expandtabs() # '01 012 0123 01234'
'01\t012\t0123\t01234'.expandtabs(4) # '01 012 0123 01234'
编码(encode())
encode(encoding="utf-8", errors="strict")
返回字符串的编码对象,默认为utf-8编码。errors
设置错误处理模式, strict
表示报UnicodeError
的错误,还可选ignore
、replace
、xmlcharrefreplace
、backslashreplace
等值。
更详尽的字符串strings内容请参阅python文档。
strings
操作汇总图片。