Programming/Python
index(), find() - 원소의 인덱스
Chan_찬
2020. 9. 1. 10:09
반응형
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
반응형
BIG