str.strip() re.sub() --从字符串中去掉不需要的字符

问题:从字符串的开始、结尾和中间去掉不需要的字符

1、去掉首尾的空格符:str.strip()默认去掉的是空格符
s.strip()
Out[3]: 'hello world'
s.lstrip()
Out[4]: 'hello world \n'
s.rstrip()
Out[5]: ' hello world'

将默认去掉的空格符指定为其他的字符:

t = '-----hello===='
t.strip('-')
Out[7]: 'hello===='
t.strip('-=')   # 可以指定多个字符模式
Out[8]: 'hello'

2、去掉字符串里面的空格: str.replace() re.sub()

s = 'hello     world'
s.replace('  ', '')
Out[10]: 'hello world'
import re
re.sub('\s+', ' ', s)
Out[12]: 'hello world'

3、结合生成器表达式使用: 它很高效,因为这里并没有先将数据读取到任何形式的临时列表中。只是创建一个迭代器。

with open('a.txt') as f:
    lines = (line.strip() for line in f)
for line in lines: pass
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容