문자열에서 특정 문자가 몇번째 인덱스에서 나타나는지 알아내는 함수
조회수 6926회
발생하는 문제 및 실행환경
문자열에서 특정 문자가 몇번째 인덱스에서 나타나는지 알아내는 함수는 어디 있습니까?
예를들면
mystring = "hello"
myindex = mystring.h #myindex = 0
이런 함수로 찾고 있습니다.
1 답변
-
find와 index 2가지 메소드가 가능합니다
간단하게 쓰는 방법은
1. str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
s[start:end]에 sub가 처음으로 등장하는 인덱스를 반환합니다. sub를 찾지 못한 경우는 -1을 반환합니다.
mystring = "hello python world!" myindex = mystring.find("l")
2. str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
find()와 비슷합니다. sub를 찾지 못한 경우는 ValueError가 발생합니다.
mystring = "hello python world!" myindex = mystring.index("l")
댓글 입력