본문 바로가기
요약정리/하우투파이썬

str: strip(), split(), partition(), replace(), join(), ...

by JustDoIT 2020. 3. 21.

lstrip()/rstrip()/strip()     split()/rsplit()/splitlines     partition()/rpartition()
replace()     join()


 

문자열을 다듬는 메서드들

 

출처: 픽사베이

 

여기서는 문자열을 다듬을 수 있는 다음 메서드들을 소개합니다. 직관적이지 않은 내용이 다소 있습니다.

 

lstrip(), rstrip()
strip()

split(), rsplit()
splitlines()

partition(), rpartition()

replace()
join()

 

lstrip(), rstrip(), strip()

lstrip()은 문자열에서 앞쪽의 화이트스페이스를 전부 제거하고 나머지를 내줍니다. 따로 문자를 지정하면 이 문자가 전부 제거된 문자열을 내줍니다. rstrip()은 같은 처리를 문자열 뒤쪽에 적용해 결과를 내주며, strip()은 앞뒤를 한꺼번에 처리해 결과를 내줍니다.

 

# str_strip.py
gr = '         hello          '
hr = '___hello___'
print(f"gr: '{gr}'")
print(f"1. gr.lstrip(): {gr.lstrip()}")
print(f"2. gr.rstrip(): {gr.rstrip()}")
print(f"3. gr.strip(): {gr.strip()}")
print('---')
print(f"hr: '{hr}'")
print(f"4. hr.lstrip('_'): {hr.lstrip('_')}")
print(f"5. hr.rstrip('_'): {hr.rstrip('_')}")
print(f"6. hr.strip('_'): {hr.strip('_')}")


# result
gr: '         hello          '
1. gr.lstrip(): hello          
2. gr.rstrip():          hello
3. gr.strip(): hello
---
hr: '___hello___'
4. hr.lstrip('_'): hello___
5. hr.rstrip('_'): ___hello
6. hr.strip('_'): hello

 

 

split(), rsplit(), splitlines

split()은 지정된 문자열을 기준으로 그 앞과 뒤를 분리해 리스트 형태로 내줍니다. 분리용 문자열을 지정하지 않으면 화이트스페이스가 기준이 됩니다. 이때 분리용 문자열이 여러 군데에 있을 때는 그 개수를 따로 제한할 수도 있습니다. rsplit()split()과 같은 동작을 오른쪽부터 적용합니다. splitlines()는 행 단위로 분리합니다. 따라서 특정 문자열을 분리용으로 지정할 수 없습니다. 그리고 keepends라는 매개변수가 False로 기본 지정되는데, 이를 True로 지정하면 새 행을 나타내는 \n이 함께 표시됩니다.

 

# str_split.py
gr = 'hello world'
print(f"gr: '{gr}'")
print(f"1. gr.split(' '): {gr.split(' ')}")
print(f"2. gr.split('o'): {gr.split('o')}")
print(f"3. gr.split('o', 1): {gr.split('o', 1)}")
print(f"4. gr.rsplit('o', 1): {gr.rsplit('o', 1)}")


# result
gr: 'hello world'
1. gr.split(' '): ['hello', 'world']
2. gr.split('o'): ['hell', ' w', 'rld']
3. gr.split('o', 1): ['hell', ' world']
4. gr.rsplit('o', 1): ['hello w', 'rld']

 

1번: 공백 문자를 기준으로 그 앞은 'hello', 그 뒤는 'world'입니다.

2번: 'o'가 기준이므로 그 앞은 'hell', 그 뒤는 ' w', 그리고 다시 'o' 뒤는 'rld'입니다.

3번: 분리용 문자를 한 번만 적용하겠다고 지정했으므로 두 번째 'o'는 무시됩니다.

4번: rsplit()은 오른쪽에서 왼쪽으로 진행합니다. 따라서 두 번째 'o' 앞은 'hello w'이고, 그 뒤는 'rld'입니다.

 

그럼 splitlines()를 살펴볼까요? 3행으로 이뤄진 문자열이므로 리스트의 요소가 세 개입니다.

 

# str_splitlnes.py
gr = '''Manners
maketh
man.'''
print(f"gr: '{gr}'")
print(f"1. gr.splitlines(): {gr.splitlines()}")
print(f"2. gr.splitlines(keepends=True): {gr.splitlines(keepends=True)}")


# result
gr: 'Manners
maketh
man.'
1. gr.splitlines(): ['Manners', 'maketh', 'man.']
2. gr.splitlines(keepends=True): ['Manners\n', 'maketh\n', 'man.']

 

 

partition(), rpartition()

partition()rpartition()은 각각 split(), rsplit()과 하는 일이 비슷합니다. 다만, 결과를 내줄 때 분리용 문자열도 함께 넣어 그 앞과 뒤를 리스트가 아닌 튜플 형식으로 만듭니다. 따라서 결과 튜플은 요소의 개수가 항상 3입니다.

 

# str_partition.py
gr = 'pyhton_learner@sample.com'
hr = '010-1234-5678'
print(f"gr: '{gr}'")
print(f"1. gr.partition('@'): {gr.partition('@')}")
print('---')
print(f"hr: '{hr}'")
print(f"2. hr.rpartition('-'): {hr.rpartition('-')}")


# result
gr: 'pyhton_learner@sample.com'
1. gr.partition('@'): ('pyhton_learner', '@', 'sample.com')
---
hr: '010-1234-5678'
2. hr.rpartition('-'): ('010-1234', '-', '5678')

 

2번은 분리용 문자열 앞과 뒤만 오른쪽에서부터 처리한 결과입니다.

 

 

replace()

replace()는 지정된 새 문자열로 교체해 내줍니다. 단, 교체할 곳이 여럿이면 횟수를 지정할 수도 있습니다.

 

# str_replace.py
gr = 'hello world'
print(f"gr: '{gr}'")
print(f"1. gr.replace('hello', 'HELLO'): {gr.replace('hello', 'HELLO')}")
print(f"2. gr.replace('l', 'L', 1): {gr.replace('l', 'L', 1)}")


# result
gr: 'hello world'
1. gr.replace('hello', 'HELLO'): HELLO world
2. gr.replace('l', 'L', 1): heLlo world

 

2번에서는 교체 횟수가 1로 지정되었으므로 먼저 등장하는 'l''L'로 바뀌었습니다.

 

 

join()

join()split()과 정반대로 일을 하는 메서드입니다. 일만 반대로 하는 것이 아니라 사용법도 반대라고 할 수 있습니다. 다음 코드를 보실까요?

 

# str_join.py
date = ['2020', '01', '01']
they = ('Robert', 'Al', 'Joe')
print(f"date: '{date}'")
print(f"1. '-'.join(date): {'-'.join(date)}")
print(f"2. '/'.join(date): {'/'.join(date)}")
print('---')
print(f"they: '{they}'")
print(f"3. ', '.join(they): {', '.join(they)}")


# result
date: '['2020', '01', '01']'
1. '-'.join(date): 2020-01-01
2. '/'.join(date): 2020/01/01
---
they: '('Robert', 'Al', 'Joe')'
3. ', '.join(they): Robert, Al, Joe

 

date의 요소들을 합치는 일종의 접착제를 '-''/'로 생각하면 쉽습니다. 3번에서는 원래 요소마다 쉼표와 공백 문자를 붙여 하나로 이었습니다.

 

여기까지입니다. 읽어 주셔서 고맙습니다.

 

Today is mutant yesterdays.
영리 목적으로는 저자의 허락 없이 편집, 배포하실 수 없습니다.
Authored by justdoit709@gmail.com

댓글