Section 41.10: 字符串包含

Python 使检查字符串是否包含给定子串变得非常直观。只需使用 in 操作符:

>>> "foo" in "foo.baz.bar"
True

注意:测试空字符串的结果总是 True:

>>> "" in "test"
True

字符串包含

Section 41.11: 将字符串列表连接成一个字符串

字符串可用作分隔符,使用 join() 方法将字符串列表连接成一个字符串。例如,您可以创建一个字符串,其中列表中的每个元素都用空格分隔。

>>> " ".join(["once","upon","a","time"])
"once upon a time"

下面的示例用三个连字符分隔字符串元素。

>>> "---".join(["once", "upon", "a", "time"])
"once---upon---a---time"

将字符串列表连接成一个字符串

Section 41.12: 计算子串在字符串中出现的次数

有一种方法可用于计算子字符串在另一个字符串中出现的次数,即 str.count。

str.count(sub[, start[, end]])

str.count 返回一个 int 表示子字符串 sub 在另一个字符串中非重叠出现的次数。可选参数 start 和 end 表示搜索的起点和终点。默认情况下,start = 0 和 end = len(str) 表示搜索整个字符串:

>>> s = "She sells seashells by the seashore."
>>> s.count("sh")
2
>>> s.count("se")
3
>>> s.count("sea")
2
>>> s.count("seashells")
1

通过为 start, end 指定不同的值,我们可以得到更本地化的搜索和计数,例如,如果start等于13,则调用:

>>> s.count("sea", start)
1

等价于

, '.']
>>> "This is a sentence.".rsplit('e', maxsplit=2)
['This is a sent', 'nc', '.']

根据分隔符将字符串拆分为字符串列表

注意:Python 规定了执行拆分的最大次数,而大多数其他编程语言则规定了创建子串的最大次数。这可能会在移植或比较代码时造成混淆。

Section 41.8: 用另一个子串替换一个子串的所有出现次数

Python 的 str 类型也有一个在给定字符串中用另一个子字符串替换一个子字符串的方法。对于要求更高的情况,可以使用 re.sub。

str.replace(old, new[, count]):

str.replace接收两个参数 old 和 new,其中 old 包含要被 new sub-string替换的old sub-string。可选参数 count 指定要替换的次数:

例如,为了用'spam'替换下面字符串中的'foo',我们可以调用old = 'foo' 和new = 'spam'的str.replace:

>>> "Make sure to foo your sentence.".replace('foo', 'spam')
"Make sure to spam your sentence."

如果给定字符串中包含多个与旧参数匹配的示例,则所有出现的示例都会被新参数中提供的值替换:

>>> "It can foo multiple examples of foo if you want.".replace('foo', 'spam')
"It can spam multiple examples of spam if you want."

当然,除非我们为 count 提供一个值。在这种情况下,出现的计数将被替换:

>>> """It can foo multiple examples of foo if you want, or you can limit the foo with the third argument.""".replace('foo', 'spam', 1)
'It can spam multiple examples of foo if you want, or you can limit the foo with the third
argument.'

用另一个子串替换一个子串的所有出现次数

Section 41.9: 测试字符串的组成

Python 的 str 类型也有许多方法可以用来评估字符串的内容。这些方法是 str.isalpha、str.isdigit、str.isalnum 和 str.isspace。还可以使用 str.isupper、str.islower 和 str.istitle测试大小写。

str.isalpha

例如,str.isalpha 不需要参数,如果给定字符串中的所有字符都是字母,则返回 True:

>>> "Hello World".isalpha() # 包含空格
False
>>> "Hello2World".isalpha() # 包含一个数字
False
>>> "HelloWorld!".isalpha() # 包含标点符号
False
>>> "HelloWorld".isalpha()
True

测试字符串的组成

作为一种边缘情况,空字符串在与 "".isalpha() 一起使用时会求值为 False。

str.isupper, str.islower, str.istitle

这些方法测试给定字符串中的大写程度。

str.isupper 是一个方法,如果给定字符串中的所有字符都是大写字母,则返回 True,否则返回 False。

"HeLLO WORLD".isupper()
False
"HELLO WORLD".isupper()
True
"".isupper()
False

相反,str.islower 是一种方法,如果给定字符串中的所有字符都是小写,则返回 true,否则返回 false。

"Hello world".islower()
False
"hello world".islower()
True
"".islower()
False

如果给定字符串是标题式的,即每个单词都以大写字母开头,然后是小写字母,则 str.istitle 返回 True。

>>> "hello world".istitle()
False
>>> "Hello world".istitle()
False
>>> "Hello World".istitle()
True
>>> "".istitle()
False

测试字符串的组成

str.isdecimal, str.isdigit, str.isnumeric

str.isdecimal 返回字符串是否为适合表示十进制数的十进制数序列。

str.isdigit 包括不适合表示十进制数的数字,例如上标数字。

str.isnumeric 包括任何数字值,即使不是数字,例如 0-9 范围以外的值。

isdecimal isdigit isnumeric
12345 True True True
?2??5 True True True
?²³????? False True True
?? False False True
Five False False False

字节字符串(Python 3 中为 bytes,Python 2 中为 str)只支持 isdigit,它只检查基本的 ASCII 数字。与 str.isalpha 一样,空字符串的值为 False。

str.isalnum

这是str.isalpha和str.isnumeric的组合,具体地说,如果给定字符串中的所有字符都是alphanumeric,即由字母或数字字符组成,则其值为true:

>>> "Hello2World".isalnum()
True
>>> "HelloWorld".isalnum()
True
>>> "2016".isalnum()
True
>>> "Hello World".isalnum() # contains whitespace
False

测试字符串的组成

str.isspace

如果字符串只包含空格字符,其值为 True。

>>> "\t\r\n".isspace()
True
>>> " ".isspace()
True

有时,一个字符串看起来是 "empty" 的,但我们不知道这是因为它只包含空白还是根本不包含任何字符

>>> "".isspace()
False

为了应对这种情况,我们需要额外的测试

>>> my_str = ''
>>> my_str.isspace()
False
>>> my_str.isspace() or not my_str
True

但测试字符串是否为空或是否只包含空白字符的最简便方法是使用 strip(不带参数,它会删除所有前导和尾部空白字符)。

>>> not my_str.strip()
True

测试字符串的组成

start[, end]])