본문 바로가기
Programming/Python

index(), find() - 원소의 인덱스

by Chan_찬 2020. 9. 1.
728x90
반응형

python - index(), find()

index(), find() 메소드는 원소의 인덱스 위치를 반환한다


index()는 해당 원소가 없으면 ValueError를 리턴하고,
find()는 -1을 리턴한다
find()는 문자열에서만 지원한다

# tuple
>>> (1,2,3,4).index(2)
1

>>> (1,2,3,4).index(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple

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


# list
>>> [1,2,3,4].index(2)
1

>>> [1,2,3,4].index(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 5 is not in list

>>> [1,2,3,4].find(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'find'


# string - index()
>>> '1234'.index('2')
1

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

# string - find()
>>> '1234'.find('2')
1

>>> '1234'.find('5')
-1
728x90
728x90
BIG

'Programming > Python' 카테고리의 다른 글

permutations in itertools  (0) 2020.09.04
list[::], tuple[::] - extended slices  (0) 2020.09.02
string unpacking - 문자열 언팩킹  (0) 2020.08.23
copy - shallow, deep : 깊은복사, 얕은복사  (0) 2020.08.19
generator - 제너레이터  (0) 2020.08.18
Buy me a coffeeBuy me a coffee

댓글