Python 从给定的字符串中删除 \n 或 \t
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17667923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove \n or \t from a given string
提问by Stella
How can I strip a string with all \n
and \t
in python other than using strip()
?
除了使用之外,如何在 python 中使用 all\n
和\t
in 去除字符串strip()
?
I want to format a string like "abc \n \t \t\t \t \nefg"
to "abcefg
"?
我想将字符串格式化"abc \n \t \t\t \t \nefg"
为"abcefg
“?
result = re.match("\n\t ", "abc \n\t efg")
print result
and result is None
结果是 None
回答by Jared
It looks like you also want to remove spaces. You can do something like this,
看起来您也想删除空格。你可以做这样的事情,
>>> import re
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = re.sub('\s+', '', s)
>>> s
'abcefg'
Another way would be to do,
另一种方法是做,
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = s.translate(None, '\t\n ')
>>> s
'abcefg'
回答by óscar López
Like this:
像这样:
import re
s = 'abc \n \t \t\t \t \nefg'
re.sub(r'\s', '', s)
=> 'abcefg'
回答by DSM
Some more non-regex approaches, for variety:
一些更多的非正则表达式方法,用于多样性:
>>> s="abc \n \t \t\t \t \nefg"
>>> ''.join(s.split())
'abcefg'
>>> ''.join(c for c in s if not c.isspace())
'abcefg'