파이썬에서 공백을 제거할 때 주로 사용하는 함수로 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
'파이썬' 카테고리의 다른 글
[python] 문자열 나누기 : split() 함수와 구분자의 활용 (1) | 2024.09.21 |
---|---|
[python] If문 간결하게 작성하는 방법 : 코드 가독성 높이기 (0) | 2024.09.12 |
[python][데이터처리] 공백으로 채워진 값을 null로 바꾸기 (0) | 2024.07.21 |
[python/pandas] read_csv에서 인코딩 문제 해결 방법 (UnicodeDecodeError) (2) | 2024.07.21 |
[python/pandas] csv 파일을 DataFrame으로 불러오기 / csv로 저장하기 (read_csv, to_csv) (1) | 2024.07.20 |