Skill/Python

[내가 보려고 적는 파이썬 함수] 문자열 함수_find, startwith, endwith, replace

엉아_ 2021. 9. 30. 01:00
728x90

💡 find

: 찾으려는 문자가 문자열의 어디에 있는지 인덱스를 반환

-> find(찾을 문자, [찾기 시작할 위치], [찾기를 끝맺을 위치])

 

alphas = 'ABCABC'
idx = alphas.find('C')
print(idx)
# 2

* 만약 찾으려는 문자가 없다면 에러가 아닌 -1을 반환

 

- 검색 시작 위치 지정 가능

alphas = 'ABCABC'
idx = alphas.find('A', 2)
print(idx)
# 3

 

- 뒤에서부터 찾기 가능: rfind(찾을 문자, [찾기 시작할 위치], [찾기를 끝맺을 위치])

alphas = 'ABCABC'
idx = alphas.rfind('A')
print(idx)
# 3

 

💡 startwith, endwith

- startwith(시작하는 문자, [시작시점])

: 어떤 문자열이 지정된 문자로 시작하는지 아닌지  True/False 반환

 

- endwith(시작하는 문자, [시작시점])

: 어떤 문자열이 지정된 문자로 끝나는지 아닌지  True/False 반환

 

string = 'My name is yeongha'
string.startwith('My')
# True
string.endwith('Younghee')
# False

 

💡 replace

: 문자열에서 지정된 문자를 다른 문자로 바꿈.

-> replace(찾을 문자, 바꿀 문자, [바꿀횟수])

 

string = 'ABCABCABC'
new_string = string.replace('A','D')
print(new_string)
# DBCDBCDBC