2.3 字符串

注解

对 Unicode 的支持使得 Python 3 可以包含世界上任何书面语言以及许多特殊符号。

2.3.1 使用引号创建字符串

在 Python 中可以使用一对 ', ", ''', """ 来创建字符串. 三元引号中的换行符无需转义, 多用于创建多行字符串. 在三元引号包裹的字符串中, 每行的换行符以及行首或行末的空格都会被保留. 举个例子:

>>> s = '''a
... b
... c
... d'''
>>> s
'a\nb\nc\nd'
>>> print(s)
a
b
c
d

警告

三元引号包裹的字符串并不是原样输出, 只是换行符无需转义, 但转义仍然是起作用的.

注解

在引号中不包含任何字符即可以创建一个空串.

2.3.2 使用 str() 进行类型转换

使用 str() 函数可以将其他 Python 数据类型转换为字符串:

>>> str(98.6)
'98.6'
>>> str(1.0e4)
'10000.0'
>>> str(True)
'True'

当调用 print() 函数或者进行字符串差值(string interpolation)时,Python 内部会自动 使用 str() 将非字符串对象转换为字符串。

2.3.3 使用 \ 转义

换行符: \n, 制表符: \t, 在引号内使用相同类型的引号需要转义: \', \", 反斜杠字符需要转义: \\.

2.3.4 使用 + 拼接字符串

在 Python 中,可以使用 + 将多个字符串或字符串变量拼接起来:

>>> 'Release the kraken! ' + 'At once!'
'Release the kraken! At once!'

2.3.5 使用 * 复制字符串

>>> test = 'ha' * 4 + 'wa' * 3
>>> test
'hahahahawawawa'

2.3.6 使用 [] 提取字符

使用 string[index] 可以提取字符串 stringindex 位置的单个字符. 注意: 0 表示第一个字符, 1 表示第二个字符, ... , -1 表示最后一个字符.

>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0]
'a'
>>> letters[1]
'b'
>>> letters[-1]
'z'
>>> letters[-2]
'y'

注解

位置索引在其他序列类型, 如列表和元组中的用法也是这样.

警告

字符串是不可变的, 无法通过给 string[index] 赋值的方式改变字符串的值.

2.3.7 使用切片提取字符串

切片操作 (slice) 可以从一个字符串中提取子字符串. [start:end:step] 称为一个切片, 得到的子串包含从 startend 之前的间隔为 step 的全部字符. 三个参数的值都是可以省略的, 如果省略 start 默认从开头提取; 省略 end 默认提取到结尾; 省略 step 默认步长为 1.

常用的切片操作及其含义如下:

  • [:] 提取从开头到结尾的整个字符串.
  • [start:] 提取从 start 到结尾的字符串.
  • [:end] 提取从开头到 end-1 的字符串.
  • [start:end] 提取从 startend-1 的字符串.
  • [start:end:step] 提取从 startend-1 间隔为 step 的字符串.
  • [::step] 提取从开头到结尾, 步长为 step 的字符串
### -------    01234567890123456789012345
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[7:]
'hijklmnopqrstuvwxyz'
>>> letters[:-3]
'abcdefghijklmnopqrstuvw'
>>> letters[7:-3]
'hijklmnopqrstuvw'
>>> letters[::2]
'acegikmoqsuwy'
>>> letters[7:-3:2]
'hjlnprtv'
>>> letters[7::2]
'hjlnprtvxz'
>>> letters[:20:2]
'acegikmoqs'

注解

如果步长为负数, 则从右到左反向进行提取操作.

>>> letters[-1::-1]
'zyxwvutsrqponmlkjihgfedcba'
>>> letters[::-1]
'zyxwvutsrqponmlkjihgfedcba'
>>> letters[0::-1]
'a'

注解

切片操作对于无效偏移量的容忍程度远大于单字符串提取. 如果在切片对应的索引位置不存在字符, 也不会报错, 而是返回空字符.

>>> letters[-50:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[-50:-40]
''
>>> letters[:70]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[60:70]
''

2.3.8 使用 len() 获取长度

>>> len(letters)
26
>>> len('')
0

注解

也可以对其他的序列类型使用 len().

警告

len() 是函数, 而不是字符串的方法.

2.3.9 使用 split() 分割字符串

split() 用于将字符串基于 分隔符 分割成由若干子串组成的列表, 以如下方式调用 string.function(arguments).

>>> todos = 'get gloves,get mask,give cat vitamins,call ambulance'
>>> todos.split(',')
['get gloves', 'get mask', 'give cat vitamins', 'call ambulance']

如果不指定分隔符, 那么默认使用空白字符 – 换行符,空格,制表符.

2.3.10 使用 join() 合并字符串

join() 用于根据指定的字符将某一列表合并为字符串. 与 split() 相反, 需要先指定粘合用的字符串, 然后再指定需要合并的列表, 即以如下方式调用 separator.join(list).

注解

不能通过 list.join(separator) 的方式来调用 join(), 因为 join() 并不是序列的方法, 而是 string 的方法, 这是为了避免对于每一个序列类型都定义一个 join() 方法.

>>> ','.join(todos.split(','))
'get gloves,get mask,give cat vitamins,call ambulance'

2.3.11 查找与判断

以纽卡斯尔伯爵 Margaret Cavendish 的不朽名篇 What Is Liquid? 为例:

>>> poem = '''All that doth flow we cannot liquid name
... Or else would fire and water be the same;
... But that is liwuid which is moist and wet
... Fir that property can never get.
... Then 'tis not cold that doth the fire put out
... But 'tis the wet that makes it die, no doubt.'''
>>> poem[:13]
'All that doth'
>>> len(poem)
249

判断是否以某个字符串开头使用 startswith, 注意是 startswith, 而不是 startwith. 判断是否以某个字符串结尾使用 endswith.

>>> poem.startwith('All')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'startwith'
>>> poem.startswith('All')
True
>>> poem.endswith("That's all, folks!")
False

查找第一次出现 the 的位置

>>> word = 'the'
>>> poem.find(word)
73

查找最后一次出现 the 的位置

>>> poem.rfind(word)
213

统计其中 the 的个数

>>> poem.count(word)
3

诗中出现的字符都是字母或数字吗?

>>> poem.isalnum()
False
>>> word.isalnum()
True

2.3.12 大小写与对齐

使用如下测试字符串:

>>> setup = 'a duck, goes into a bar.'

strip() 用于删除首尾的某些字符串, lstrip() 删除左边的, rstrip() 删除右边的. 传入参数为空时删除空白字符.

>>> setup.strip(',.')
'a duck, goes into a bar'
>>> setup.strip('a.')
' duck, goes into a bar'
>>> setup.strip('a. ')
'duck, goes into a bar'
>>> setup.strip('ar. ')
'duck, goes into a b'
>>> setup.strip('bar. ')
'duck, goes into'
>>> setup.strip('abr. ')
'duck, goes into'
>>> setup.lstrip('abr. ')
'duck, goes into a bar.'
>>> setup.rstrip('abr. ')
'a duck, goes into'

在大小写与标题样式之间转换.

>>> setup.capitalize()
'A duck, goes into a bar.'
>>> setup.title()
'A Duck, Goes Into A Bar.'
>>> setup.upper()
'A DUCK, GOES INTO A BAR.'
>>> setup.lower()
'a duck, goes into a bar.'
>>> setup.swapcase()
'A DUCK, GOES INTO A BAR.'
>>> setup.title().swapcase()
'a dUCK, gOES iNTO a bAR.'

将字符串排版在指定长度内并居中或左对齐或右对齐, 不足部分以空格补齐.

>>> setup.center(30)
'   a duck, goes into a bar.   '
>>> setup.ljust(30)
'a duck, goes into a bar.      '
>>> setup.rjust(30)
'      a duck, goes into a bar.'

2.3.13 使用 replace() 替换

replace() 函数用于简单的字符串替换, 调用格式为 string.replace(old, new, num), 最后一个参数用于指定需要替换多少处, 如果省略则默认替换所有.

>>> setup.replace('a','one')
'one duck, goes into one boner.'
>>> setup.replace('a','one', 1)
'one duck, goes into a bar.'

如果只想替换单词的话记得添加空格, 不过如果单词后面包含标点符号的话还是无能为力.

>>> setup.replace('a ','a famous ')
'a famous duck, goes into a famous bar.'

注解

如果想进行更精确的匹配和替换, 请使用 正则表达式.

2.3.14 更多关于字符串的内容

阅读 Python 文档字符串方法部分 https://docs.python.org/3/library/stdtypes.html#string-methods 获取关于字符串的更多内容.


Last update: Jul 13, 2017