파이썬

[파이썬/python] strip 함수 - 공백 제거, 특정 문자 제거

도도o 2024. 9. 5. 15:25

파이썬에서 공백을 제거할 때 주로 사용하는 함수로 strip이 있다.

비슷하게 사용되는 lstrip, rstrip 도 함께 살펴보자.

 

 

 

공백 제거

strip 함수는 문자열 함수의 앞뒤에 있는 공백을 제거한다. 문자열의 왼쪽이나 오른쪽에 공백이 있다면, 인자 없이 strip함수를 적용해주면 된다.

string = '   hello   '
print(string.strip())

 

출력결과

hello

 

 

 

lstrip, rstrip 함수는 각각 왼쪽, 오른쪽의 공백만 제거한다.

print('[', string.lstrip(), ']')
print('[', string.rstrip(), ']')

 

출력결과

[hello   ]
[   hello]

 

 

 

특정 문자 제거

strip 함수는 문자열에서 원하는 특정 문자도 제거할 수 있다. 함수의 인자로 제거하고자 하는 문자를 넣을 수 있다.

string = '000hello0000'

print(string.strip(0))
print(string.lstrip(0))
print(string.rstrip(0))

 

출력결과

hello
hello0000
000hello

 

 

 

 

여러 문자 제거

비슷한 방법으로 여러 문자를 지정할 수 있다. 해당 문자가 포함된 횟수와 상관없이, 문자가 있다면 모두 제거한다.

string = '....a,,hello..kkk'

print(string.strip(,a.k))
print(string.lstrip(,a.k))
print(string.rstrip(,a.k))

 

출력결과

hello
hello..kkk
....a,,hello

 

 

 

 

 

 

 

참고한 자료

https://m.blog.naver.com/0dod0_/222849843342