무냐의 개발일지
Python 파이썬 strip(), split() 차이점 본문
strip과 split은 Python에서 문자열을 처리할 때 자주 사용하는 메서드이다.
|strip
문자열의 양쪽 끝에 있는 공백이나 특정 문자를 제거
string.lstrip([chars])와 string.rstrip([chars])는 각각 문자열의 왼쪽 또는 오른쪽 끝에서 문자를 제거.
s = " hello world "
print(s.strip()) # "hello world"
print(s.lstrip()) # "hello world "
print(s.rstrip()) # " hello world"
s = "xxhelloxworldxx"
print(s.strip('x')) # "helloxworld"
print(s.lstrip('x')) # "helloxworldxx"
print(s.rstrip('x')) # "xxhelloxworld"
| split
문자열을 지정한 구분자를 기준으로 나누어 리스트로 반환
구분자를 지정할 수 있으며, 이 인자를 생략하면 기본적으로 모든 공백(스페이스, 탭 등)을 구분자로 사용
s = "hello world welcome"
print(s.split()) # ['hello', 'world', 'welcome']
s = "apple,banana,cherry"
print(s.split(',')) # ['apple', 'banana', 'cherry']
s = "one two three four"
print(s.split(' ', 2)) # ['one', 'two', 'three four']
| 차이점 요약
- strip: 문자열의 양쪽 끝에 있는 공백이나 특정 문자를 제거합니다. 문자열의 내용을 변경하지 않고 단순히 양 끝의 불필요한 문자를 제거하는 데 사용됩니다.
- split: 문자열을 지정한 구분자를 기준으로 나누어 리스트로 반환합니다. 문자열을 특정 기준으로 분할하여 각 부분을 별도의 문자열로 다룰 수 있게 합니다.
'LeetCode 코딩테스트' 카테고리의 다른 글
[HTML] Github (깃헙)에 프로젝트 업로드 & 웹 호스팅하는 법 / 문제 해결 (총정리!!! ) (2) | 2024.07.20 |
---|---|
Python 파이썬 isalpha(), isalnum() 차이점 (0) | 2024.07.09 |
Python 파이썬 sort(), sorted() 차이점 (0) | 2024.07.08 |
Python append(), extend() 차이점 (0) | 2024.07.04 |
26. Remove Duplicates from Sorted Array -_- (0) | 2024.07.04 |