파이썬 문자열에서 하위 문자열이 처음 나타나는 것을 어떻게 찾을 수 있습니까?
"그 남자는 멋진 남자야"라는 문자열을 고려하면,
'dude'의 첫 번째 인덱스를 찾고 싶습니다.
mystring.findfirstindex('dude') # should return 4
이에 대한 python 명령어는 무엇입니까?
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
빠른 개요:index
그리고.find
옆에find
방법도 있습니다.index
.find
그리고.index
둘 다 동일한 결과를 산출합니다. 첫 번째 발생 위치를 반환하지만 아무것도 발견되지 않을 경우index
a를 올릴 것입니다.ValueError
반면에.find
돌아온다-1
즉, 두 가지 모두 동일한 벤치마크 결과를 얻을 수 있습니다.
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
추가 지식: rfind
그리고.rindex
:
일반적으로, 전달된 문자열이 시작되는 가장 작은 인덱스를 찾아 인덱스합니다.
rfind
그리고.rindex
시작할 때 가장 큰 인덱스를 반환합니다. 대부분의 문자열 검색 알고리즘은 왼쪽에서 오른쪽으로 검색하므로 다음으로 시작하여 기능합니다.r
오른쪽에서 왼쪽으로 검색이 수행됨을 나타냅니다.
그래서 당신이 찾고 있는 요소의 가능성이 목록의 시작보다 끝에 가까울 경우,rfind
또는rindex
더 빠를 겁니다.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
출처: Python: Visual QuickStart 가이드, Toby Donaldson
파이썬 내장 함수를 사용하지 않음으로써 알고리즘 방식으로 이를 구현합니다.이는 다음과 같이 구현할 수 있습니다.
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude'
print(find_pos(string,word))
# output 4
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
verse = "만약 당신의 모든 것이 그들의 것을 잃고 당신을 탓할 수 있다면,\n모든 남자들이 당신을 의심할 때 당신이 자신을 믿을 수 있다면,\n하지만 그들의 의심에 대해서도 용서하십시오.\n기다릴 수 있고 지치지 않을 수 있다면, 거짓말을 하지 마세요, 미움을 받지 마세요.\n그러나 너무 좋아 보이지도, 너무 현명하게 말하지도 마세요:"
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
언급URL : https://stackoverflow.com/questions/3221891/how-can-i-find-the-first-occurrence-of-a-sub-string-in-a-python-string
'programing' 카테고리의 다른 글
명시적으로 파일을 닫는 것이 중요합니까? (0) | 2023.06.27 |
---|---|
MS SQL Server에서 예약된 단어/키워드인 테이블 이름 만들기 (0) | 2023.06.27 |
GridView가 양식 태그 내에 있는 후에도 runat="server"가 있는 양식 태그 내에 GridView를 배치해야 합니다. (0) | 2023.06.27 |
Oracle에 대한 Linkq를 사용하는 방법이 있습니까? (0) | 2023.06.27 |
SQL Server 데이터베이스의 소유자를 변경하려면 어떻게 해야 합니까? (0) | 2023.06.22 |