2012-05-22 15 views
38

मैं लिनक्स पर पायथन 2.7 में सभी रिक्त स्थान/टैब/न्यूलाइन को हटाने का प्रयास कर रहा हूं।स्ट्रिप रिक्त स्थान/टैब/न्यूलाइन - पायथन

मैं इस, उस काम करना चाहिए लिखा है:

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

कोई ऐसा नहीं होना चाहिए। –

+1

उपयोगी हो सकता है: http://stackoverflow.com/questions/8928557/python-splitting-string-by-all-space-characters – newtover

+1

यह मेरे लिए काम करता है: [व्हाइटस्पेस ट्रिम कैसे करें (टैब सहित)?] [1] एस = s.strip ('\ t \ n \ r') [1]: http://stackoverflow.com/questions/1185524/how-to-trim-whitespace- सहित टैब – stamat

उत्तर

25

आप एक से अधिक खाली स्थान के आइटम को हटा दें और उन्हें एक रिक्त स्थान के साथ बदलना चाहते हैं, तो सबसे आसान तरीका है इस तरह की एक regexp साथ है:

>>> 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() साथ अनुगामी अंतरिक्ष हटा सकते हैं यदि आप चाहते हैं।

73

उपयोग str.split([sep[, maxsplit]]) कोई sep या sep=None साथ:

से docs:

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) 

उत्पादन:

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, newlinesandtabs

संबंधित मुद्दे