string.contains
string.indexof
if not somestring.contains("blah"):
continue
string.contains
string.indexof
if not somestring.contains("blah"):
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
사용 사례의 99% 는 또는 다음Python에 문자열에 하위 문자열 메서드가 포함되어 있습니까?
in
True
False
'substring' in any_string
인덱스를 가져오는 사용 사례의 경우 다음을 사용합니다
str.find
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
또는
str.index
find
start = 100
end = 1000
any_string.index('substring', start, end)
in
>>> 'foo' in '**foo**'
True
원래 질문이 요구한 반대(보완)는
not in
>>> 'foo' not in '**foo**' # returns False
False
이것은 의미상으로 동일
not 'foo' in '**foo**'
__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
and 를 사용하지 마십시오 .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에서는
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] 한 줄에 여러 예외 잡기(블록 제외) (0) | 2022.08.21 |
---|---|
[python] 현재 시간을 어떻게 알 수 있습니까? (0) | 2022.08.21 |
[Python] 함수에서 전역 변수 사용 (0) | 2022.07.31 |
[Python] 'for' 루프를 사용하여 사전 반복 (0) | 2022.07.31 |
[Python] 목록에서 항목의 인덱스 찾기 (0) | 2022.07.31 |