파이썬 python 문자열 찾기

파이썬 문자열 내장 함수에서 문자열을 찾는 함수에 대해 알아보겠습니다.

  • count: 찾는 문자열의 갯수를 반환합니다.
  • find: 찾는 문자열의 position 값을 반환합니다.
  • index: 찾는 문자열의 position 값을 반환합니다.
  • startswith: 대상 문자열이 지정된 문자열로 시작하는지 판단합니다.
  • endswith: 대상 문자열이 지정된 문자열로 끝나는지 판단합니다.

- count

대상 문자열에서 찾는 문자열의 갯수를 반환합니다.

txt = 'Hello, Hello, welcome to the python world.' print(txt.count('Hello')) # print: 2 print(txt.count('welcome')) # print: 1 print(txt.count('goodbye')) # print: 0

- find

대상 문자열에서 찾는 문자열의 position 값을 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.find('python')) # print: 22 print(txt.find('welcome')) # print: 7 print(txt.find('goodbye')) # print: -1

INFO: 문자열이 존재하지 않는 경우 -1 을 반환합니다.


- index

대상 문자열에서 찾는 문자열의 position 값을 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.index('python')) # print: 22 print(txt.index('welcome')) # print: 7 print(txt.index('goodbye')) # print: ValueError: substring not found

INFO: 문자열이 존재하지 않는 경우 ValueError를 반환합니다.
find와 index의 차이는 문자열을 찾지 못했을 경우
find는 -1 을 반환하고 index는 ValueError를 반환한다는 것입니다.

- startswith

대상 문자열에서 지정된 문자열로 시작하는지를 판단합니다.
맞으면 True 틀리면 False를 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.startswith('Hello')) # print: True print(txt.startswith('welcome')) # print: False

- endswith

startswith과 반대로 대상 문자열에서 지정된 문자열로 끝나는지를 판단합니다.
맞으면 True 틀리면 False를 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.endswith('world.')) # print: True print(txt.endswith('python')) # print: False

+ Recent posts