development

Python에서 문자열의 모든 공백 제거

big-blog 2020. 9. 30. 09:20
반응형

Python에서 문자열의 모든 공백 제거


문자열, 양쪽 끝, 단어 사이의 모든 공백을 제거하고 싶습니다.

이 Python 코드가 있습니다.

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

그러나 이것은 문자열 양쪽의 공백 만 제거합니다. 모든 공백을 어떻게 제거합니까?


선행 및 끝 공백을 제거하려면 str.strip()다음을 사용하십시오 .

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

모든 공백을 제거하려면 str.replace()다음을 사용하십시오 .

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

중복 된 공간을 제거하려면 str.split()다음을 사용하십시오 .

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

공백 만 제거하려면 다음을 사용하십시오 str.replace.

sentence = sentence.replace(' ', '')

모든 공백 문자 (공백, 탭, 줄 바꿈 등) 를 제거하려면 split다음 을 사용할 수 있습니다 join.

sentence = ''.join(sentence.split())

또는 정규식 :

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

처음과 끝에서 공백 만 제거하려면 다음을 사용할 수 있습니다 strip.

sentence = sentence.strip()

를 사용 lstrip하여 문자열 시작 부분에서만 공백을 제거하고 문자열 rstrip끝에서 공백을 제거 할 수도 있습니다 .


대안은 정규식을 사용하고 이러한 이상한 공백 문자일치 시키는 것 입니다. 여기 몇 가지 예가 있어요.

단어 사이에서도 문자열의 모든 공백을 제거합니다.

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

문자열의 시작 부분에서 공백을 제거하십시오.

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

문자열 끝의 공백을 제거하십시오.

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

문자열의 BEGINNING과 END 모두에서 공백을 제거하십시오.

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

중복 된 공간 만 제거 :

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(모든 예제는 Python 2와 Python 3에서 모두 작동합니다.)


공백에는 공백, 탭 및 CRLF가 포함 됩니다. 따라서 우리가 사용할 수 있는 우아하고 한 줄짜리 문자열 함수는 translate입니다 .

' hello  apple'.translate(None, ' \n\t\r')

또는 철저히하고 싶다면 :

import string
' hello  apple'.translate(None, string.whitespace)

For removing whitespace from beginning and end, use strip.

>> "  foo bar   ".strip()
"foo bar"

' hello  \n\tapple'.translate( { ord(c):None for c in ' \n\t\r' } )

MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).


Be careful:

strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).

If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.


import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

참고URL : https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python

반응형