스트링에 모든 공백 문자를 제거하고 싶은데 앞 뒤 공백만 제거됩니다
조회수 55174회
발생하는 문제 및 실행환경
스트링 첫, 중간, 끝부분에 있는 모든 공백을 없애려면 어떻게 해야 되나요? 제 코드는 처음이랑 끝부분에 있는 공백만 없애는데 저는 모든 공백을 제거하고 싶어요
소스코드
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
1 답변
-
공백 문자를 자르는 방법은 여러 가지가 있습니다. 지우고 싶은 공백이 스페이스를 말하는 건지, 개행 문자 같은 모든 공백 문자를 말하는 건지 잘 모르겠어서 다 써놓겠습니다.
1. 양쪽 끝의 공백 문자를 제거하는 경우 - str.strip:
sentence = ' hello apple' sentence.strip() #'hello apple'
2. 모든 스페이스(' ')를 제거하는 경우 - str.replace():
sentence = ' hello apple' sentence.replace(" ", "") #'helloapple'
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()과 str.join():
sentence = ' hello apple' " ".join(sentence.split()) # 'hello apple'
댓글 입력