【python cookbook】【字符串与文本】11.从字符串中去掉不需要的字符

问题:在字符串的开始、结尾或中间去掉不需要的字符,比如说空格符

解决方案:

1、字符串开始或结尾处去掉字符:str.strip()

2、从左或从右侧开始执行去除字符:str.lstrip()、str.rstrip()

3、对位于字符串中间的进行去除字符:str.replace()、re.sub()

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s=' hello world 
'
>>> s.strip()
'hello world'
>>> s.lstrip()
'hello world 
'
>>> s.rstrip()
' hello world'
>>> t='----hello===='
>>> t.lstrip('-')
'hello===='
>>> t.rstrip('=')
'----hello'
>>> t.strip('-=')
'hello'
>>> s2=' hello   world   
'
>>> s2.strip()#对中间的空格不起作用
'hello   world'
>>> s2.replace(' ','')
'helloworld
'
>>> import re
>>> re.sub('s+',' ',s2)
' hello world '
>>> re.sub('s+','',s2)
'helloworld'
>>> 

通常遇到的情况是将去除字符的操作同某些迭代器结合起来,比如说从文件中读取文本行。此时,就是生成器表达式大显身手的时候了,例如:

with open('test.txt') as f:
    lines=(line.strip() for line in f)
    for line in lines:
        print(line)
>>> ================================ RESTART ================================
>>> 
hello    world
hello  world
hello    world
>>> 

lines=(line.strip() for line in f)的作用是完成数据的转换,它很高效,因为这里并没有先将数据读取到任何形式的临时列表中,它只是创建一个迭代器,在所有产生出的文本行上都会执行strip()操作。

对于更高级的strip()操作,请见下一节的translate()方法。

原文地址:https://www.cnblogs.com/apple2016/p/5792297.html