IT story

하위 문자열이 다른 문자열에 있는지 확인하는 방법

hot-time 2020. 8. 11. 18:59
반응형

하위 문자열이 다른 문자열에 있는지 확인하는 방법


하위 문자열이 있습니다.

substring = "please help me out"

다른 문자열이 있습니다.

string = "please help me out so that I could solve this"

Python 사용 substring의 하위 집합 인지 어떻게 알 수 string있습니까?


와 함께 in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something

(그런데- string같은 이름의 파이썬 표준 라이브러리가 있기 때문에 변수 이름을 지정하지 마십시오. 대규모 프로젝트에서 그렇게하면 사람들을 혼동 할 수 있으므로 이와 같은 충돌을 피하는 것이 좋은 습관입니다.)


True / False 이상을 찾고 있다면 다음과 같이 re 모듈을 사용하는 것이 가장 적합합니다.

import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())

s.group() "제발 도와주세요"문자열을 반환합니다.


사람들은 string.find(),, string.index()그리고 string.indexOf()주석에서 언급 했고 여기에 요약했습니다 ( Python Documentation 에 따라 ).

우선 string.indexOf()방법 이 없습니다 . Deviljho가 게시 한 링크는 이것이 JavaScript 함수임을 보여줍니다.

둘째 string.find()string.index()실제로 문자열의 인덱스를 돌려줍니다. : 유일한 차이점은 문자열 찾을 수없는 상황을 처리하는 방법입니다 string.find()수익을 -1하면서 string.index()을 제기한다 ValueError.


난 당신이 그들이 당신이 사용하지 않는 기술 면접이 작업을 수행하는 방법을 찾고있는 경우에는이를 추가 할 것이라고 생각 파이썬의 기능을 내장 in또는 find끔찍하지만, 일이 않는 :

string = "Samantha"
word = "man"

def find_sub_string(word, string):
  len_word = len(word)  #returns 3

  for i in range(len(string)-1):
    if string[i: i + len_word] == word:
  return True

  else:
    return False

find () 메서드를 사용해 볼 수도 있습니다. 문자열 str이 문자열에서 발생하는지 또는 문자열의 하위 문자열에서 발생 하는지를 결정합니다.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

In [7]: substring = "please help me out"

In [8]: string = "please help me out so that I could solve this"

In [9]: substring in string
Out[9]: True

def find_substring():
    s = 'bobobnnnnbobmmmbosssbob'
    cnt = 0
    for i in range(len(s)):
        if s[i:i+3] == 'bob':
            cnt += 1
    print 'bob found: ' + str(cnt)
    return cnt

def main():
    print(find_substring())

main()

이 방법을 사용할 수도 있습니다.

if substring in string:
    print(string + '\n Yes located at:'.format(string.find(substring)))

enter image description here

find ()를 사용하는 대신 쉬운 방법 중 하나는 위와 같이 'in'을 사용하는 것입니다.

if 'substring' is present in 'str' then if part will execute otherwise else part will execute.

참고URL : https://stackoverflow.com/questions/7361253/how-to-determine-whether-a-substring-is-in-a-different-string

반응형