Program Club

찾기와 색인의 차이점

proclub 2021. 1. 7. 08:16
반응형

찾기와 색인의 차이점


나는 파이썬을 처음 접했고 찾기와 색인의 차이점을 이해할 수 없습니다.

>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

항상 동일한 결과를 반환합니다. 감사!!


str.find-1하위 문자열을 찾지 못하면 반환합니다 .

>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1

str.index인상 하는 동안 ValueError:

>>> line.index('?')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

하위 문자열이 발견되면 두 함수 모두 동일한 방식으로 작동합니다.


또한 find는 목록, 튜플 및 문자열에 인덱스를 사용할 수있는 문자열에만 사용할 수 있습니다.

>>> somelist
['Ok', "let's", 'try', 'this', 'out']
>>> type(somelist)
<class 'list'>

>>> somelist.index("try")
2

>>> somelist.find("try")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'find'

>>> sometuple
('Ok', "let's", 'try', 'this', 'out')
>>> type(sometuple)
<class 'tuple'>

>>> sometuple.index("try")
2

>>> sometuple.find("try")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'find'

>>> somelist2
"Ok let's try this"
>>> type(somelist2)
<class 'str'>

>>> somelist2.index("try")
9
>>> somelist2.find("try")
9

>>> somelist2.find("t")
5
>>> somelist2.index("t")
5

참조 URL : https://stackoverflow.com/questions/22190064/difference-between-find-and-index

반응형