Python은 문자열 'contains' 서브스트링 메서드를 가지고 있습니까?
를 찾고 있습니다.string.contains
또는string.indexof
메서드(Python 。
하고 싶은 일:
if not somestring.contains("blah"):
continue
연산자를 사용합니다.
if "blah" not in somestring:
continue
서브스트링 검색일 경우string.find("substring")
.
, 및 는 서브스트링 검색이므로 조금 주의해야 합니다.즉, 다음과 같습니다.
s = "This be a string"
if s.find("is") == -1:
print("No 'is' here!")
else:
print("Found 'is' in the string.")
인쇄가 됩니다.Found 'is' in the string.
유사하게,if "is" in s:
평가하다True
이것은 당신이 원하는 것일 수도 있고 아닐 수도 있습니다.
Python에는 서브스트링 메서드가 포함된 문자열이 있습니까?
사용 사례의 99%는 키워드를 사용하여 커버됩니다.in
이 값은 반환됩니다.True
또는False
:
'substring' in any_string
인덱스를 가져오는 사용 사례의 경우,str.find
(실패 시 -1을 반환하고 옵션 positional 인수를 사용합니다).
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
또는str.index
(마치find
단, 장애 발생 시 ValueError를 발생시킵니다).
start = 100
end = 1000
any_string.index('substring', start, end)
설명.
를 사용합니다.in
비교 연산자:
- 언어는 그 사용을 의도하고 있다.
- 다른 Python 프로그래머들은 당신이 그것을 사용하기를 기대합니다.
>>> 'foo' in '**foo**'
True
원래 질문의 반대(충족)는 다음과 같습니다.not in
:
>>> 'foo' not in '**foo**' # returns False
False
이것은 의미론적으로 다음과 같습니다.not 'foo' in '**foo**'
가독성 향상으로 훨씬 가독성이 뛰어나고 언어로 명시되어 있습니다.
사용을 피하다__contains__
「contains」메서드는, 다음의 동작을 실장합니다.in
이 예에서는
str.__contains__('**foo**', 'foo')
돌아온다True
이 함수는 슈퍼스트링 인스턴스에서도 호출할 수 있습니다.
'**foo**'.__contains__('foo')
하지만 그러지 마세요.밑줄로 시작하는 메서드는 의미론적으로 비공개로 간주됩니다.이 기능을 사용하는 유일한 이유는 이 기능을 구현하거나 확장할 때뿐입니다.in
그리고.not in
기능성(예를 들어 하위 분류의 경우)str
):
class NoisyString(str):
def __contains__(self, other):
print(f'testing if "{other}" in "{self}"')
return super(NoisyString, self).__contains__(other)
ns = NoisyString('a string with a substring inside')
그리고 지금:
>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True
사용하지 않다find
그리고.index
검사하다
다음 문자열 메서드를 사용하여 "포함"을 테스트하지 마십시오.
>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2
>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'**oo**'.index('foo')
ValueError: substring not found
다른 언어에는 서브스트링을 직접 테스트하는 방법이 없을 수 있습니다.따라서 이러한 방식을 사용해야 합니다.그러나 Python에서는, Python을 사용하는 것이 훨씬 효율적입니다.in
비교 연산자
또, 이것들은, 다음의 대체품이 아닙니다.in
. 예외를 처리해야 할 수도 있습니다.-1
케이스 및 케이스가 돌아오면0
(처음에 서브스트링을 발견했기 때문에) 부울 해석은 다음과 같습니다.False
True
.
이 정말 말한다면not any_string.startswith(substring)
그럼 말해 봐
퍼포먼스 비교
우리는 같은 목표를 달성하기 위한 다양한 방법을 비교할 수 있다.
import timeit
def in_(s, other):
return other in s
def contains(s, other):
return s.__contains__(other)
def find(s, other):
return s.find(other) != -1
def index(s, other):
try:
s.index(other)
except ValueError:
return False
else:
return True
perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}
, 그럼 이제 쓰시면 되겠네요.in
을 사용하다동등한 작업을 수행하는 시간을 단축하는 것이 좋습니다.
>>> perf_dict
{'in:True': 0.16450627865128808,
'in:False': 0.1609668098178645,
'__contains__:True': 0.24355481654697542,
'__contains__:False': 0.24382793854783813,
'find:True': 0.3067379407923454,
'find:False': 0.29860888058124146,
'index:True': 0.29647137792585454,
'index:False': 0.5502287584545229}
할 수 있을까요?in
가 빠르다__contains__
in
__contains__
이것은 훌륭한 후속 질문입니다.
관심 있는 방법으로 함수를 분해해 보겠습니다.
>>> from dis import dis
>>> dis(lambda: 'a' in 'b')
1 0 LOAD_CONST 1 ('a')
2 LOAD_CONST 2 ('b')
4 COMPARE_OP 6 (in)
6 RETURN_VALUE
>>> dis(lambda: 'b'.__contains__('a'))
1 0 LOAD_CONST 1 ('b')
2 LOAD_METHOD 0 (__contains__)
4 LOAD_CONST 2 ('a')
6 CALL_METHOD 1
8 RETURN_VALUE
''는 '우리 '우리'는.__contains__
메서드는 별도로 검색하여 Python 가상 머신에서 호출해야 합니다.이것에 의해서, 그 차이가 충분히 설명됩니다.
if needle in haystack:
@Michael이 말한 것처럼 일반적인 사용법입니다.메서드 호출보다 읽기 쉽고 빠릅니다.
를 들어 한 방법을 )key=
아주 특이한 종류로...?)는 다음과 같습니다.그러나, 당신의 예는, 에서의 사용을 위해서입니다.if
을 직접 가특수한 방법을 직접 사용하는 것은 좋은 형태(가독성도, 효율도)가 아닙니다.대신 연산자와 빌트인을 통해 사용하도록 되어 있습니다.
in
과 lists Python
에서는 이 문제에 할 수 몇 .in
★★★★
>>> "foo" in "foobar"
True
>>> "foo" in "Foobar"
False
>>> "foo" in "Foobar".lower()
True
>>> "foo".capitalize() in "Foobar"
True
>>> "foo" in ["bar", "foo", "foobar"]
True
>>> "foo" in ["fo", "o", "foobar"]
False
>>> ["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]
수 있습니다.또, 「 」도 참조해 주세요. 목록은 반복할 수 있습니다.in
메서드는 문자열뿐만 아니라 반복 가능한 데이터에도 적용됩니다.
문자열의 "유사" 정도를 측정하기 위해 보다 애매한 방법으로 문자열을 비교하려면 Levenshtein 패키지를 사용하는 것을 고려하십시오.
에 드신다면"blah" in somestring
콜이 싶은 는, 이 /기능 콜을 할 수 .
import operator
if not operator.contains(somestring, "blah"):
continue
Python의 모든 연산자는 다음을 포함한 연산자 모듈에서 찾을 수 있습니다.in
.
그래서 보아하니 벡터-와이즈 비교에는 비슷한 것이 없다.Python의 확실한 방법은 다음과 같습니다.
names = ['bob', 'john', 'mike']
any(st in 'bob and john' for st in names)
>> True
any(st in 'mary and jane' for st in names)
>> False
하시면 됩니다.y.count()
.
하위 문자열이 문자열에 나타나는 횟수의 정수 값을 반환합니다.
예를 들어 다음과 같습니다.
string.count("bah") >> 0
string.count("Hello") >> 1
답변은 다음과 같습니다.
if "insert_char_or_string_here" in "insert_string_to_search_here":
#DOSTUFF
거짓 여부를 확인하는 경우:
if not "insert_char_or_string_here" in "insert_string_to_search_here":
#DOSTUFF
또는:
if "insert_char_or_string_here" not in "insert_string_to_search_here":
#DOSTUFF
정규식을 사용하여 다음 항목을 가져올 수 있습니다.
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
언급URL : https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
'programing' 카테고리의 다른 글
get_lock에서 현재 잠금을 모두 표시합니다. (0) | 2022.09.15 |
---|---|
이미지를 업로드하기 전에 미리 보기 (0) | 2022.09.15 |
MinGW-w64 및 MSYS2 설치 방법 (0) | 2022.09.15 |
Manjaro Linux: 소켓이 없어 Mariadb를 실행할 수 없습니다. (0) | 2022.09.15 |
Stripe API 오류 수정 방법: "IntegrationError:지정된 요소에서 데이터를 검색할 수 없습니다." Vue 구성 요소에서? (0) | 2022.09.15 |