그냥 공부

strip과 split

dnjswngo 2025. 2. 25. 18:03

1. strip

문자열 양쪽 끝에 있는 공백이나 특정 문자 제거

str='  hello world  '
print(str.strip()) #'hello world'
print(str.lstrip()) #'hello world  '
print(str.rstrip()) #'  hello world'
str='xxhelloxworldxx'
print(str.strip('x')) #'helloxworld'
print(str.lstrip('x')) #'helloxworldxx'
print(str.rstrip('x')) #'xxhelloxworld'

 

2. split

공백이나 특정 문자 기준으로 나눠서 리스트로 반환

str = 'hello world'
print(str.split()) #['hello', 'world']

str = 'hello,world'
print(str.split(',')) #['hello', 'world']

str = 'one two three four'
print(str.split(' ',2)) #['one', 'two', 'three four']

저기 2는 최대 분할 횟수 .. 쟤는 공백(' ')을 기준으로 최대 2번만 분할한다.

그리고 저렇게 변수명 str로 쓰면 남대식 교수님한테 혼난다.

왜냐하면 str은 파이썬의 내장 자료형이니까요.