망각에 재주 있는 나를 위해 기록하는 곳.

[PYTHON] 문자열 나누기 split(), 문자열 결합하기 join(), 문자열 대체하기 replace(), 문자열 스트립 strip() 본문

PYTHON

[PYTHON] 문자열 나누기 split(), 문자열 결합하기 join(), 문자열 대체하기 replace(), 문자열 스트립 strip()

baobabtree 2022. 3. 27. 01:46

split()

구분자를 기준으로 리스트로 나누기 위한 문자열 내장 함수.

 

구분자가 ','인 경우

text = "get apple,get banana,give phone,buy computer,sell watch"
print(text.split(','))  # ['get apple', 'get banana', 'give phone', 'buy computer', 'sell watch']

구분자가 없는 경우 (공백을 기준으로 나눈다)

text = "get apple,get banana,give phone,buy computer,sell watch"
print(text.split())  # ['get', 'apple,get', 'banana,give', 'phone,buy', 'computer,sell', 'watch']

 

 

join()

문자열 리스트를 하나의 문자열로 결합한다.

join() 메서드는 문자열 리스트를 string.join(list) 형태로 결합한다. 그러므로 lines 리스트를 각각 줄바꿈하여 하나의 문자열로 결합하기 위해 '\n'.join(lines)을 입력한다.

ex_list = ['abc','def','ghi','jkm']
ex_string = ', '.join(ex_list)
print(ex_string)    # abc, def, ghi, jkm

 

 

replace()

문자열 일부를 대체할 수 있다.

replace( 바꿀 문자열, 대체할 문자열, 횟수)

횟수를 생략하면 모든 인스턴스를 바꾼다.

text = "nice to meet you! nice~ good~"
print(text.replace('nice', 'glad'))     # glad to meet you! glad~ good~
text = "nice to meet you! nice~ good~"
print(text.replace('nice', 'glad', 1))     # glad to meet you! nice~ good~

 

 

strip()

패딩 문자(여백 또는 공백 문자)를 제거하거나 인수에 해당하는 문자를 제거한다. 

strip() 메서드에 인수가 없으면 양쪽 공백를 제거한다.

왼쪽 끝만 제거하면 lstrip(), 오른쪽 끝만 제거하면 rstrip()을 사용한다.

text = " test "
print(text.strip())     # 'test'
print(text.strip(' '))  # 'test'
print(text.lstrip())    # 'test '
print(text.rstrip())    # ' test'

strip() 메서드에 해당하는 인수가 없을 경우 아무런 일도 일어나지 않는다.

text = " test....?? "
print(text.strip('!'))  #  test....??

다음은 strip()의 다양한 경우의 수이다.

text = " test....?? "
print(text.strip('!'))      #  test....?? 
print(text.strip('.?'))     #  test....??
print(text.strip(' .?'))    # test
print(text.strip('.? '))    # test
print(text.rstrip('.? '))   #  test
print(text.lstrip('.? '))   # test....??