2.11 删除字符串中�需�的字符¶

问题¶

你想去掉文本字符串开头,结尾或者中间�想�的字符,比如空白。

解决方案¶

strip() 方法能用于删除开始或结尾的字符。 lstrip() 和 rstrip() 分别从左和从�执行删除�作。 默认情况下,这些方法会去除空白字符,但是你也�以指定其他字符。比如:

>>> # Whitespace stripping
>>> s = ' hello world \n'
>>> s.strip()
'hello world'
>>> s.lstrip()
'hello world \n'
>>> s.rstrip()
' hello world'
>>>
>>> # Character stripping
>>> t = '-----hello====='
>>> t.lstrip('-')
'hello====='
>>> t.strip('-=')
'hello'
>>>

讨论¶

这些 strip() 方法在读�和清�数�以备�续处�的时候是�常会被用到的。 比如,你�以用它们�去掉空格,引�和完�其他任务。

但是需�注�的是去除�作�会对字符串的中间的文本产生任何影�。比如:

>>> s = ' hello     world \n'
>>> s = s.strip()
>>> s
'hello     world'
>>>

如果你想处�中间的空格,那么你需�求助其他技术。比如使用 replace() 方法或者是用正则表达�替�。示例如下:

>>> s.replace(' ', '')
'helloworld'
>>> import re
>>> re.sub('\s+', ' ', s)
'hello world'
>>>

通常情况下你想将字符串 strip �作和其他迭代�作相结�,比如从文件中读�多行数�。 如果是这样的�,那么生�器表达�就�以大显身手了。比如:

with open(filename) as f:
    lines = (line.strip() for line in f)
    for line in lines:
        print(line)

在这里,表达� lines = (line.strip() for line in f) 执行数�转��作。 这�方��常高效,因为它�需�预先读�所有数�放到一个临时的列表中去。 它仅仅�是创建一个生�器,并且�次返回行之�会先执行 strip �作。

对于更高阶的strip,你�能需�使用 translate() 方法。请�阅下一节了解更多关于字符串清�的内容。