如何在Python中使用除strip()
之外的所有\n
和\t
字符串?從給定的字符串中刪除 n或 t
我想格式化像"abc \n \t \t\t \t \nefg"
到"abcefg
「的字符串?
result = re.match("\n\t ", "abc \n\t efg")
print result
和結果是None
如何在Python中使用除strip()
之外的所有\n
和\t
字符串?從給定的字符串中刪除 n或 t
我想格式化像"abc \n \t \t\t \t \nefg"
到"abcefg
「的字符串?
result = re.match("\n\t ", "abc \n\t efg")
print result
和結果是None
看起來你也想刪除空格,你可以做這樣的事情,
>>> import re
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = re.sub('\s+', '', s)
>>> s
'abcefg'
另一種方法是,
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = s.translate(None, '\t\n ')
>>> s
'abcefg'
像這樣:
import re
s = 'abc \n \t \t\t \t \nefg'
re.sub(r'\s', '', s)
=> 'abcefg'
參數'翻譯()'在Python> 3改變。它現在需要一個可以由'str.maketrans()'生成的翻譯表。 https://docs.python.org/3/library/stdtypes.html#str.translate – gruentee