Program Tip

Python에서 문자열 찾기의 예

programtip 2020. 12. 2. 21:47
반응형

Python에서 문자열 찾기의 예


몇 가지 예를 찾으려고 노력하고 있지만 운이 없습니다. 누구든지 인터넷에서 몇 가지 예를 알고 있습니까? 찾을 수 없을 때 반환되는 내용과 시작부터 끝까지 지정하는 방법을 알고 싶습니다. 0, -1이 될 것 같습니다.


당신도 사용할 수 있습니다 str.index:

>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1

무엇을 찾고 있는지 잘 모르겠습니다. 의미 find()합니까?

>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1

에서 문서 :

str.find(sub[, start[, end]])

슬라이스 내 에서 substring sub 가 발견 된 문자열의 가장 낮은 인덱스를 반환합니다 s[start:end]. 선택적 인수 startend 는 슬라이스 표기법으로 해석됩니다. sub 를 찾을 수 없으면 반환 -1합니다 .

따라서 몇 가지 예 :

>>> my_str = 'abcdefioshgoihgs sijsiojs '
>>> my_str.find('a')
0
>>> my_str.find('g')
10
>>> my_str.find('s', 11)
15
>>> my_str.find('s', 15)
15
>>> my_str.find('s', 16)
17
>>> my_str.find('s', 11, 14)
-1

솔직히 이것은 명령 줄에서 Python을 열고 엉망으로 만드는 상황입니다.

 >>> x = "Dana Larose is playing with find()"
 >>> x.find("Dana")
 0
 >>> x.find("ana")
 1
 >>> x.find("La")
 5
 >>> x.find("La", 6)
 -1

파이썬의 인터프리터는 이런 종류의 실험을 쉽게 만듭니다. (유사한 통역사를 사용하는 다른 언어도 마찬가지입니다.)


텍스트에서 문자열의 마지막 인스턴스를 검색하려면 rfind를 실행할 수 있습니다.

예:

   s="Hello"
   print s.rfind('l')

출력 : 3

* 불필요

완전한 구문 :

stringEx.rfind(substr, beg=0, end=len(stringEx))

find( sub[, start[, end]])

substring sub가 발견 된 문자열에서 가장 낮은 인덱스를 반환하여 sub가 [start, end] 범위에 포함되도록합니다. 선택적 인수 start 및 end는 슬라이스 표기법으로 해석됩니다. sub를 찾을 수 없으면 -1을 반환합니다.

에서 워드 프로세서 .


이 시도:

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

참고URL : https://stackoverflow.com/questions/674764/examples-for-string-find-in-python

반응형