2012-05-22 11 views
38

Linuxのpython 2.7のスペース/タブ/改行をすべて削除しようとしています。私は仕事をするべきである、これを書いたストリップスペース/タブ/改行 - python

myString="I want to Remove all white \t spaces, new lines \n and tabs \t" 
myString = myString.strip(' \n\t') 
print myString 

出力:

I want to Remove all white spaces, new lines 
and tabs 

を何をする単純なことのように思える、まだ私はここで何かが欠けています。私は何かを輸入すべきか?この関連の質問への答えうち

+2

いいえnewlinesandtabs。 –

+1

が役に立つかもしれません:http://stackoverflow.com/questions/8928557/python-splitting-string-by-all-space-characters – newtover

+1

これは私のために働いていました:[空白を整える方法(タブを含む)?] [1] S = s.strip( '\ Tの\ n個の\ R') [1]:http://stackoverflow.com/questions/1185524/how-to-trim-whitespace- include-tabs – stamat

答えて

25

あなたが複数の空白の項目を削除し、単一のスペースでそれらを交換したい場合は、最も簡単な方法は、このような正規表現である:

>>> import re 
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t" 
>>> re.sub('\s+',' ',myString) 
'I want to Remove all white spaces, new lines and tabs ' 

あなたがしたい場合は、その後.strip()と末尾のスペースを削除することができます。 docsから

73

sep又はsep=Noneなしで使用str.split([sep[, maxsplit]])

sepが指定又はNoneであり、異なる分割アルゴリズムは が適用されない場合は、次の連続する空白の実験は以下のように考えられています単一の 区切り文字で、結果には開始時に空の文字列が含まれません。 または文字列の先頭または末尾に空白がある場合は、終了します。この出力を得るために、返されたリストに

>>> myString.split() 
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs'] 

使用str.join

デモ

>>> ' '.join(myString.split()) 
'I want to Remove all white spaces, new lines and tabs' 
10
import re 

mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t" 
print re.sub(r"\W", "", mystr) 

Output : IwanttoRemoveallwhitespacesnewlinesandtabs 
+1

これは ';'も削除します。 – jan

1

これは、改行をタブを削除します、スペースと他に何もありません。

import re 
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t" 
output = re.sub(r"[\\n\\t\s]*", "", mystr) 

OUTPUT:

IwaoRemoveallwhiespaces、良い一日

をewliesadabs!

1

再ライブラリ

import re 
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t" 
myString = re.sub(r"[\n\t\s]*", "", myString) 
print myString 

出力を使用します

IwanttoRemoveallwhitespacesを、それはいけない