Language/Python
파이썬 find, replace, strip 사용하기 - 전처리
jvvp512
2020. 7. 13. 19:08
728x90
문자열 찾기
문자열을 찾을 때는 find() 함수를 사용합니다.
text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
find = text.find('ipsum')
find2 = text.find('pink')
print(find)
print(find2)
if find > -1:
print(f'found {find} index.')
if find2 > -1:
print(f'found {find2} index.')
else:
print('Not found')
더보기
6
-1
found 6 index.
Not found.
리스트처럼 index() 도 사용가능합니다.
찾는 문자열이 존재 하지 않을 경우 에러를 발생합니다.
text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
find = text.index('dolor')
print(find)
find2 = text.index('pink')
print(find2)
더보기
12
Traceback (most recent call last):
File "c:/Users/Desktop/Python/string_/ex_find.py", line 21, in <module>
find2 = text.index('pink')
ValueError: substring not found
문자열 치환하기
문자열을 치환할 때는 replace() 함수를 사용합니다.
replace('', '') 첫 번째 인자가 두 번째 인자로 치환되며, 그 문자열을 반환합니다.
예제를 통해 보겠습니다.
text = 'Pellentesque sed ultricies diam.'
rp_text = text.replace('sed', '***')
print(rp_text)
더보기
Pellentesque *** ultricies diam.
문자열 끝 문자 제거하기
이 경우에 쓸 수 있는 함수는 lstrip(), strip(), rstrip() 이 있습니다.
lstrip() 은 왼쪽, rstrip() 은 오른쪽, strip() 은 양쪽다 제거합니다.
text = ' \nPellentesque '
lstrip = text.lstrip()
strip = text.strip()
rstrip = text.rstrip()
print(lstrip.encode())
print(strip.encode())
print(rstrip.encode())
더보기
b'Pellentesque '
b'Pellentesque'
b' \nPellentesque'
보통은 공백을 제거할 때 사용하지만, 문자열도 가능합니다.
>>> text = 'GGGHelloGGG'
>>> text.strip('GGG')
'Hello'