从给定的字符串中删除\n或\ t

Ste*_*lla 10 python string

如何使用除了使用之外的所有\n\tpython中的字符串去除strip()

我想格式化字符串一样"abc \n \t \t\t \t \nefg""abcefg"?

result = re.match("\n\t ", "abc \n\t efg")
print result
Run Code Online (Sandbox Code Playgroud)

结果是 None

Jar*_*red 14

看起来你也想删除空格.你可以这样做,

>>> import re
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = re.sub('\s+', '', s)
>>> s
'abcefg'
Run Code Online (Sandbox Code Playgroud)

另一种方式是,

>>> s = "abc \n \t \t\t \t \nefg"
>>> s = s.translate(None, '\t\n ')
>>> s
'abcefg'
Run Code Online (Sandbox Code Playgroud)


DSM*_*DSM 8

一些更多的非正则表达式方法,为了变化:

>>> s="abc \n \t \t\t \t \nefg"
>>> ''.join(s.split())
'abcefg'
>>> ''.join(c for c in s if not c.isspace())
'abcefg'
Run Code Online (Sandbox Code Playgroud)


Ósc*_*pez 6

像这样:

import re

s = 'abc \n \t \t\t \t \nefg'
re.sub(r'\s', '', s)
=> 'abcefg'
Run Code Online (Sandbox Code Playgroud)