programing

파이썬 문자열에서 하위 문자열이 처음 나타나는 것을 어떻게 찾을 수 있습니까?

minimums 2023. 6. 27. 22:02
반응형

파이썬 문자열에서 하위 문자열이 처음 나타나는 것을 어떻게 찾을 수 있습니까?

"그 남자는 멋진 남자야"라는 문자열을 고려하면,
'dude'의 첫 번째 인덱스를 찾고 싶습니다.

mystring.findfirstindex('dude') # should return 4

이에 대한 python 명령어는 무엇입니까?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

빠른 개요:index그리고.find

옆에find방법도 있습니다.index.find그리고.index둘 다 동일한 결과를 산출합니다. 첫 번째 발생 위치를 반환하지만 아무것도 발견되지 않을 경우indexa를 올릴 것입니다.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

반응형