파이썬에서 문자열에서 공백을 제거하는 방법

소개

이 자습서는 Python에서 문자열에서 공백을 제거하는 다양한 방법의 예를 제공합니다.

A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.

이 자습서의 예에서는 Python 대화형 콘솔을 사용하여 공백을 제거하는 다양한 방법을 보여줍니다. 예제는 다음 문자열을 사용합니다:

s = '  Hello  World   From DigitalOcean \t\n\r\tHi There  '

결과는 다음과 같습니다:

Output
Hello World From DigitalOcean Hi There

이 문자열에는 공백( ), 탭(\t), 새 줄(\n), 그리고 캐리지 리턴(\r)과 같은 다양한 유형의 공백 문자가 있습니다.

strip() 메서드를 사용하여 선행 및 후행 공백 제거

Python 문자열 strip() 메서드는 문자열에서 선행 및 후행 문자를 제거합니다. 제거할 기본 문자는 공백입니다.

문자열 변수를 선언하세요:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

strip() 메서드를 사용하여 선행 및 후행 공백을 제거하십시오:

  1. s.strip()

결과는:

Output
'Hello World From DigitalOcean \t\n\r\tHi There'

만약 선행 공백이나 후행 공백만 제거하려면 lstrip()rstrip() 메서드를 사용할 수 있습니다.

replace() 메서드를 사용하여 모든 공백 제거

replace() 메서드를 사용하여 단어 사이를 포함하여 문자열에서 모든 공백 문자를 제거할 수 있습니다.

문자열 변수를 선언하십시오:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

replace() 메서드를 사용하여 공백을 빈 문자열로 대체하십시오:

  1. s.replace(" ", "")

결과는:

Output
'HelloWorldFromDigitalOcean\t\n\r\tHiThere'

join()split() 메서드를 사용하여 중복된 공백 및 개행 문자 제거

중복된 공백 문자와 개행 문자를 모두 제거하려면 join() 메서드와 split() 메서드를 함께 사용하면 됩니다. 이 예에서 split() 메서드는 어떤 공백 문자든 기본 구분자로 사용하여 문자열을 리스트로 분할합니다. 그런 다음 join() 메서드는 각 단어 사이에 단일 공백 문자(" ")를 두고 리스트를 다시 하나의 문자열로 결합합니다.

문자열 변수를 선언하세요:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

join()split() 메서드를 함께 사용하여 중복된 공백 및 개행 문자를 제거하세요:

  1. " ".join(s.split())

출력은 다음과 같습니다:

Output
'Hello World From DigitalOcean Hi There'

translate() 메서드를 사용하여 모든 공백 및 개행 문자 제거하기

translate() 메서드를 사용하여 모든 공백 및 개행 문자를 제거할 수 있습니다. translate() 메서드는 지정된 문자를 사전이나 매핑 테이블에 정의된 문자로 바꿉니다. 다음 예제는 string.whitespace 문자열 상수를 포함하는 사용자 정의 사전을 사용합니다. 사용자 정의 사전 {ord(c): None for c in string.whitespace}string.whitespace의 모든 문자를 None으로 대체합니다.

string 모듈을 가져와서 string.whitespace를 사용할 수 있도록합니다:

  1. import string

문자열 변수를 선언하세요:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

사용하실 코드는 translate() 메소드를 사용하여 모든 공백 문자를 제거하세요:

  1. s.translate({ord(c): None for c in string.whitespace})

결과는 다음과 같습니다:

Output
'HelloWorldFromDigitalOceanHiThere'

정규식을 사용하여 공백 문자 제거

re.sub() 함수를 사용하여 정규 표현식에 일치하는 공백 문자를 제거할 수도 있습니다.

다음 예제는 파일 regexspaces.py를 사용하여 정규식을 사용하여 공백 문자를 제거하는 몇 가지 방법을 보여줍니다:

regexspaces.py
import re

s = '  Hello  World   From DigitalOcean \t\n\r\tHi There  '

print('Remove all spaces using regex:\n', re.sub(r"\s+", "", s), sep='')  # \s는 모든 공백 문자를 일치합니다
print('Remove leading spaces using regex:\n', re.sub(r"^\s+", "", s), sep='')  # ^는 시작을 일치합니다
print('Remove trailing spaces using regex:\n', re.sub(r"\s+$", "", s), sep='')  # $는 끝을 일치합니다
print('Remove leading and trailing spaces using regex:\n', re.sub(r"^\s+|\s+$", "", s), sep='')  # |는 OR 조건을 나타냅니다

명령 줄에서 파일을 실행하세요:

python3 regexspaces.py

다음 출력이 표시됩니다:

Remove all spaces using regex:
HelloWorldFromDigitalOceanHiThere
Remove leading spaces using regex:
Hello  World   From DigitalOcean 	
	Hi There  
Remove trailing spaces using regex:
  Hello  World   From DigitalOcean 	
	Hi There
Remove leading and trailing spaces using regex:
Hello  World   From DigitalOcean 	
	Hi There

결론

이 튜토리얼에서는 Python에서 문자열에서 공백 문자를 제거하는 데 사용할 수 있는 몇 가지 방법을 배웠습니다. 계속해서 Python 문자열에 대해 학습하세요.

Source:
https://www.digitalocean.com/community/tutorials/python-remove-spaces-from-string