2013-07-16 31 views
6

如何在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

回答

10

看起來你也想刪除空格,你可以做這樣的事情,

>>> 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' 
+0

參數'翻譯()'在Python> 3改變。它現在需要一個可以由'str.maketrans()'生成的翻譯表。 https://docs.python.org/3/library/stdtypes.html#str.translate – gruentee

3

像這樣:

import re 

s = 'abc \n \t \t\t \t \nefg' 
re.sub(r'\s', '', s) 
=> 'abcefg' 
6

一些更多的非正則表達式的方法,對於各種:

>>> s="abc \n \t \t\t \t \nefg" 
>>> ''.join(s.split()) 
'abcefg' 
>>> ''.join(c for c in s if not c.isspace()) 
'abcefg' 
+1

這比re要快得多。 – seth

+0

@seth:我認爲'translate'通常會在這些遊戲中勝出,在適用的地方。我只是不在乎正則表達式。 :^) – DSM