PROGRAMMING/Python

[PYTHON] string 공백 제거, 없애기 (replace, split, strip, re sub)

HYUNHP 2023. 2. 15. 22:06
728x90
반응형

안녕하세요, HELLO

 

오늘은 파이썬을 활용하여, string 데이터에서 공백을 제거하는 방법에 대해서 정리하려고 합니다.

파이썬에서는 대표적으로 replace, split 그리고 re 라이브러리를 활용해서 삭제할 수 있습니다.

 

 

STEP 1. string 공백 제거, 없애기

■ Replace 함수 사용하여 공백 제거하기

 

string = "   hello   world   "
string = string.replace(" ", "")
print(string)  # Output: "helloworld"

■ split 함수와 join 함수 사용하여 공백 제거하기

 

string = "   hello   world   "
string = "".join(string.split())
print(string)  # Output: "helloworld"

 

반응형

 

■ strip 함수 사용하여 공백 제거하기

 

string = "  hello world  "
string = string.strip()
print(string)  # Output: "hello world"

 

추가적으로, 왼쪽 공백만 삭제하고 싶으면 lstrip 함수를 사용하면 됩니다.

 

string = "  hello world"
string = string.lstrip()
print(string)  # Output: "hello world"
 
그리고, 오른쪽 공백만 삭제하고 싶으면 rstrip 함수를 사용하면 됩니다.
 
string = "hello world  "
string = string.rstrip()
print(string)  # Output: "hello world"

■ re 라이브러리 내 sub 함수 사용하여 공백 제거하기

 

import re

my_string = "   Hello,    World!   "
new_string = re.sub(r"\s+", "", my_string)
print("Original string:", my_string)
print("New string:", new_string)

# Original string:    Hello,    World!   
# New string: Hello,World!

■ 마무리

'string 공백 제거, 없애기 (replace, split, strip, re sub)'에 대해서 알아봤습니다.

좋아요댓글 부탁드리며,

오늘 하루도 즐거운 날 되시길 기도하겠습니다 :)

감사합니다.

반응형