2012-05-22 3 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

없음 말아야을 newlinesandtabs 없습니다. –

+1

이 유용 할 수 있습니다. http://stackoverflow.com/questions/8928557/python-splitting-string-by-all-space-characters – newtover

+1

이것은 [나를 공백으로 장식하는 방법 (탭 포함)]에서 나에게 도움이 되었습니까?] [1] s.strip S = ('\ t의 \ n \ r 일') [1] : http://stackoverflow.com/questions/1185524/how-to-trim-whitespace- including-tabs – stamat

답변

25

, 가장 쉬운 방법은이 같은 정규 표현식 함께 : 당신이 원하는 경우 다음 .strip()에 후행 공백을 제거 할 수 있습니다

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

.

없는 sep 또는 sep=None
73

사용 str.split([sep[, maxsplit]]) : sep 지정 또는 None,하지 않은 경우

다른 분할 알고리즘은 적용됩니다 :

docs에서 연속 공백의 실행은으로 간주된다 단일 구분 기호이며 결과에 공백이없는 공백이있는 경우 시작 부분에 빈 문자열이 포함되지 않습니다. 또는 끝.

데모 : 반환 된 목록에 대한 사용 str.join이 출력을 얻을 수

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

:이 내용은 탭, 줄 바꿈을 제거합니다

>>> ' '.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는