字符串¶
你已经和他们合作了一段时间: strings
.原则上,字符串是按一定顺序排列的字符容器。因此,它们与 lists
<list>`,还支持,例如索引。
>>> my_first_string = 'Hello, World!'
>>> my_first_string[7:]
'World!'
>>> my_first_string[::-1]
'!dlroW ,olleH'
它们提供了大量处理文本的方法,下面列出了一些选定的方法。
lower
¶
返回字符串的小写版本。
>>> 'Hello, World!'.lower()
'hello, world!'
upper
¶
返回字符串的大写版本。
>>> 'Hello, World!'.upper()
'HELLO, WORLD!'
split
¶
在许多情况下,同时处理整个字符串是不必要的复杂。因此,python标准库提供了一种 string
分开: str.split()
>>> some_string = 'My first string'
>>> some_string.split()
['My', 'first', 'string']
默认情况下,它拆分为任意数量的空白
>>> some_string = 'My second string'
>>> some_string.split()
['My', 'second', 'string']
注解
在python中,空白是您不能直接看到的所有内容,比如空格、制表符。 (\t
在字符串中)和换行符中 (\n
在字符串中)。
但也可以指定另一个字符串,用于将其他字符串拆分:
>>> some_string = '0.1, 0.2, 0.3, 0.4, 0.5'
>>> some_string.split(',')
['0.1', ' 0.2', ' 0.3', ' 0.4', ' 0.5']
用于拆分的字符串将在进程中使用。因此,为了消除额外的空白,您可以将其添加到用于拆分的字符串中。
>>> some_string = '0.1, 0.2, 0.3, 0.4, 0.5'
>>> some_string.split(', ')
['0.1', '0.2', '0.3', '0.4', '0.5']
如果不严格保持字符串格式,最终可能会导致问题:
>>> some_string = '0.1, 0.2,0.3, 0.4, 0.5'
>>> some_string.split(', ')
['0.1', ' 0.2,0.3', '0.4', ' 0.5']
但 Python 让你得到保护…
strip
¶
要消除字符串周围不需要的空白,可以使用 str.strip()
方法:
>>> some_string = '\n\n So much surrounding whitespace\n\n'
>>> print(some_string)
So much surrounding whitespace
>>> some_string.strip()
'So much surrounding whitespace'
您还可以通过将字符指定为参数来消除空格以外的内容:
>>> more_string = '...Python...'
>>> more_string.strip('.')
'Python'
注解
指定为参数的字符不被视为字符串,而是要从字符串中删除的字符集合:
>>> incantation = 'abracadabra'
>>> incantation.strip('bra')
'cad'
总结¶
使用
str.split()
拆分string
在子字符串处。使用
str.strip()
去除边缘的多余字符,特别是空白字符。