python - 포함 - 파이썬 키워드 검색
파이썬에는 문자열 'substring'을 포함하고 있습니까? (10)
파이썬에서 string.contains
또는 string.indexof
메소드를 찾고있다.
나하고 싶어:
if not somestring.contains("blah"):
continue
파이썬에 문자열에 substring 메서드가 있습니까?
그렇습니다. 그러나 파이썬에는 언어가 사용을 의도하기 때문에 대신 사용해야하는 비교 연산자가 있으며 다른 프로그래머는이를 사용할 것으로 기대합니다. 해당 키워드는 비교 연산자로 사용됩니다.
>>> 'foo' in '**foo**'
True
최초의 질문에서 요구하는 반대 (보완)는 다음과 같은 것이 not in
.
>>> 'foo' not in '**foo**' # returns False
False
이것은 not 'foo' in '**foo**'
와 의미 상 동일하지만 가독성 향상을 위해 언어에서 훨씬 더 읽기 쉽고 명시 적으로 제공됩니다.
__contains__
, find
및 index
사용을 피하십시오.
약속대로 여기에 contains
메소드가 있습니다.
str.__contains__('**foo**', 'foo')
True
반환합니다. 수퍼 스트링의 인스턴스에서이 함수를 호출 할 수도 있습니다.
'**foo**'.__contains__('foo')
그러나하지 마라. 밑줄로 시작하는 메소드는 의미 상 사적으로 간주됩니다. 이것을 사용하는 유일한 이유 not in
기능을 in
과 not in
확장 할 때입니다 (예 : str
서브 클래 싱하는 경우).
class NoisyString(str):
def __contains__(self, other):
print('testing if "{0}" in "{1}"'.format(other, 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
또한 다음 문자열 메서드를 사용하지 마십시오.
>>> '**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에서는 비교 연산자를 사용하는 것이 훨씬 효율적입니다.
실적 비교
우리는 같은 목표를 성취하는 다양한 방법을 비교할 수 있습니다.
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
을 사용 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
메서드와 관련된 몇 가지 유용한 예제입니다.
"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
경고. 리스트는 iterable이며, in
메소드는 문자열뿐만 아니라 iterables에서도 작동합니다.
다른 단어에 포함 된 하위 문자열 대신 전체 단어를 대 / 소문자를 구분하지 않고 검색하려는 경우 :
import string
s = 'This is my text example'
if 'is' not in (word.lower()
for split_char in string.punctuation + string.whitespace
for word in s.split(split_char)):
# do something
따라서 명백히 벡터 비교를위한 비슷한 것은 없습니다. 이렇게하는 명백한 파이썬 방법은 다음과 같습니다.
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
부울 반환 값 (예 : True
또는 False)을 사용하여 문자열에 몇 개의 문자가 포함되어 있는지 여부를 찾는 또 다른 방법은 다음과 같습니다.
str1 = "This be a string"
find_this = "tr"
if find_this in str1:
print find_this, " is been found in ", str1
else:
print find_this, " is not found in ", str1
아니요, string.contains(str)
메서드는 없지만 in
연산자가 있습니다.
if substring in someString:
print "It's there!!!"
다음은보다 복잡한 작업 예제입니다.
# Print all files with dot in home directory
import commands
(st, output) = commands.getstatusoutput('ls -a ~')
print [f for f in output.split('\n') if '.' in f ]
이미 답이 있지만 두 센트를 추가하고 싶습니다.
파이썬에는이 작업을 수행하는 함수가 있지만 가장 간단하고 (주로 선호되는) 방법은 다음과 같은 키워드를 사용하는 것 in
.
"test" in "testtext"
True
"abc" in "abcdefg"
True
"abc" in "Abc"
False
"ABC" in "abc"
False
"abc" in "def"
False
"abc" in ["abc", "def", "ghi"]
True
문자열 메소드도 있습니다 :
"xxabcxx".find("abc")
2 #returns the index of the first match
"xxabcxx".find("cde")
-1 #returns -1 if the substring
#could not be found in the string
# and:
"xxabcxx".index("abc")
2
"xxabcxx".index("cde")
ValueError: substring not found
#raises ValueError...
실적 정보 :
일반적으로 부분 문자열을 찾는 단식 방법은 ...
find
가 index
보다 약간 빠름
희망을 도울 수있어!
파이썬에는 이것을 달성 할 수있는 두 가지 간단한 방법이 있습니다.
파이썬 적 방법 : 파이썬의 'in'키워드 사용하기 -
in
은 왼쪽 인수 ( substring )와 오른쪽 인수 중 하나를 인수 in
취하고 인수가 rightside 인수에 포함되어 있으면 True
반환하고 그렇지 않으면 False
반환합니다.
example_string = "This is an example string"
substring = "example"
print(substring in example_string)
산출:
True
비 - 파이썬 적 방법 : Python의 str.find 사용하기 :
find
메소드는 문자열 내의 문자열의 위치를 반환하거나 문자열이 없으면 -1을 반환합니다. 그러나 위치가 -1이 아닌지 단순히 확인하십시오.
if example_string.find(substring) != -1:
print('Substring found!')
else:
print('Substring not found!')
산출:
Substring found!
"blah" in somestring
만족하지만 함수 호출이되기를 원한다면, 아마도 이것을 할 수있을 것입니다
import operator
if not operator.contains(somestring, "blah"):
continue
파이썬의 모든 연산자는 in을 포함한 연산자 모듈 에서 찾을 수 있습니다.
if needle in haystack:
@Michael이 말했듯이 보통의 사용법입니다. in
연산자에 의존하며, 메소드 호출보다 읽기 쉽고 빠릅니다.
연산자 대신에 메소드가 필요하다면 (예 : 이상한 key=
매우 특이한 정렬을 할 때 ...?), 'haystack'.__contains__
이 될 것입니다. 그러나 당신의 예제는 if
에서 사용하기위한 것이기 때문에, 당신이 말하는 것을 정말로 의미하는 것은 아닙니다 .-)). 특별한 메소드를 직접 사용하는 것은 좋은 형식이 아니며, 읽기 쉽고 효율적이지 않습니다. 대신에 위임 된 연산자와 내장 함수를 통해 사용됩니다.