11. 删除字符串中不需要的字符
strip()
方法能用于删除开始或结尾的字符;
lstrip()
和 rstrip()
分别从左和从右执行删除操作
>>> s = ' hello world \n' >>> s = s.strip() >>> s 'hello world' >>>
如果你想处理中间的空格,那么你需要求助其他技术。比如使用 replace()
方法或者是用正则表达式re.sub()替换。示例如下:
>>> s.replace(' ', '') 'helloworld' >>> import re >>> re.sub('\s+', ' ', s) 'hello world' >>>
\s+: 匹配空格1次~多次
对于更高阶的strip,你可能需要使用translate()
方法
12. 审查清理文本字符串