字符串¶
您与他们共事已有一段时间了: strings
。原则上,字符串是特定顺序的字符容器。因此,它们在某种程度上类似于 lists
并且还支持例如索引。
>>> my_first_string = 'Hello, World!'
>>> my_first_string[7:]
'World!'
>>> my_first_string[::-1]
'!dlroW ,olleH'
它们提供了大量处理文本的方法,下面将概述其中几种精选的方法。
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()
去掉边缘的多余字符,尤其是空格。