파이썬 문자열 index() 메서드
예시
텍스트에서 "환영합니다"라는 단어는 어디에 있습니까?:
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
정의 및 사용
index()
메서드는 지정된 값의 첫 번째 항목을 찾습니다 .
index()
값을 찾을 수 없으면 메서드에서 예외가 발생합니다 .
메서드 는 index()
메서드와 거의 동일하지만
find()
유일한 차이점은 find()
값을 찾을 수 없는 경우 메서드가 -1을 반환한다는 것입니다. (아래 예 참조)
통사론
string.index(value, start, end)
매개변수 값
Parameter | Description |
---|---|
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
더 많은 예
예시
텍스트에서 문자 "e"가 처음 나타나는 위치는 어디입니까?
txt = "Hello, welcome to my world."
x = txt.index("e")
print(x)
예시
위치 5와 10 사이에서만 검색할 때 문자 "e"가 처음 나타나는 텍스트는 어디입니까?:
txt = "Hello, welcome to my world."
x = txt.index("e",
5, 10)
print(x)
예시
값을 찾을 수 없으면 find() 메서드는 -1을 반환하지만 index() 메서드는 예외를 발생시킵니다.
txt = "Hello, welcome to my world."
print(txt.find("q"))
print(txt.index("q"))