[파이썬] 문자열의 공백 제거(strip)

데이터 처리나 문자열 다루기를 할 때, 문자열의 공백을 제거하는 것은 자주 사용되는 작업입니다. Python은 이를 쉽게 처리할 수 있는 내장 함수를 제공합니다.

strip() 함수

Python의 문자열 클래스는 strip() 메소드를 갖고 있습니다. 이 메소드는 문자열의 앞뒤에 있는 모든 공백을 제거해줍니다.

사용법

string = "   Hello,   World!   "

# 앞뒤 공백 제거
stripped_string = string.strip()

print(stripped_string)  # 출력: "Hello,   World!"

lstrip()과 rstrip() 함수

만약 문자열의 앞이나 뒤의 공백만 제거하고 싶다면, lstrip() 또는 rstrip() 메소드를 사용할 수 있습니다.

사용법

string = "   Hello,   World!   "

# 왼쪽 공백 제거
left_stripped_string = string.lstrip()

# 오른쪽 공백 제거
right_stripped_string = string.rstrip()

print(left_stripped_string)   # 출력: "Hello,   World!   "
print(right_stripped_string)  # 출력: "   Hello,   World!"

문자열 안의 공백 제거하기

만약 문자열 안에 있는 공백만 제거하고 싶다면, replace() 메소드를 사용할 수 있습니다.

사용법

string = "Hello,   World!"

# 문자열 안의 공백 제거
stripped_string = string.replace(" ", "")

print(stripped_string)  # 출력: "Hello,World!"

결론

Python은 문자열의 공백을 제거하는 작업을 간단하게 처리할 수 있도록 다양한 메소드를 제공합니다. strip(), lstrip(), rstrip(), replace() 함수를 이용하여 필요한 공백 제거 작업을 수행할 수 있습니다. 이러한 기능들을 효율적으로 사용하여 데이터 처리나 문자열 다루기를 보다 간편하게 할 수 있습니다.