반응형
파이썬에서 공백을 처리 하는 방법
1. 문자열 양쪽의 공백을 제거 - str.strip([chars])
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
2. 모든 스페이스(' ')를 제거 - str.replace(old, new[, count])
>>> ' hello world '.replace(" ", "")
'helloworld'
3. 모든 공백문자를 제거 - re모듈(정규식)
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
#또는
sentence = ' hello apple\t\t\n\n\n\n'
''.join(sentence.split()) #'helloapple'
4. 중복된 공백문자(스페이스 2개) 제거 - str.split([sep[, maxsplit]]), str.join(iterable)
sentence = ' hello apple'
" ".join(sentence.split()) # 'hello apple'
반응형