I want to do.
if not somestring.contains("blah"):
continue
['에서' 운영자] [1] 사용할 수 있습니다.
if "blah" not in somestring:
continue
[1]: https://docs.python.org/reference/expressions.html # 맴버십을 테스트 정보
약간의 주의를 해야 할 수 있는 ['찾기'] (https://docs.python.org/library/stdtypes.html # 스트리핀드), ['인덱스화할'] (https://docs.python.org/library/stdtypes.html # 스트리아네스), 그리고 ['에서'] (https://docs.python.org/reference/expressions.html # 테스트 작업을 맴버십을) 하지만, 있기 때문에 문자열 검색. 다시 말해서, 이:
s = "This be a string"
if s.find("is") == -1:
print "No 'is' here!"
else:
print "Found 'is' in the string."
'바늘' 는 일반적인 사용 등 it 의 경우 짚단 @michael 말한다 - ['에서'] [1] 에서는 메서드 호출 연산자, 가독성을 높이고 보다 더 빠릅니다.
대신 신앙인들이라면 medianame 메서드입니다 연산자에서 (예를 들어, '키 =' 을 위한 몇 가지 이상한 매우 특이한 형태의 정렬함으로써.?), [# 39, & # 39 haystack& .contains ','] 그 약간만이라도 [2]. 그러나 너회의 비유하사 사용할 수 있는 '만약' t really 짓궂군요 너희는너희가 # 39 라고 don& 뭐;; -). # 39 의 좋지 않은 it& 양식 (disk_b_s10database 판독값, disk_b_s10database 효율형) - # 39 건, re they& 특별한 방법을 사용하여 직접 사용할 수 있는 것이 아니라, 그들을 통해 종합유선방송사업자 (so) 와 기본 제공 위임합니다.
[1]: https://docs.python.org/reference/expressions.html # 맴버십을 테스트 정보 [2]: https://docs.python.org/reference/datamodel.html # object.contains
>. # 는 파이썬 %s/dbase/ext_table. map_layer 문자열으로 substring 방법?
Python 은 있음-그러나 언어 사용, 그 때문에 비교 연산자 콩지름에 대신 쓰고 있는 다른 프로그래머들이 사용할 수 있을 것으로 보인다. 그 키워드가 '에서' 로 사용되는 비교 연산자:
>>> 'foo' in '**foo**'
True
반대편 (보수) 를 묻는 질문에 '는', 오리지널 않는다.
>>> 'foo' not in '**foo**' # returns False
False
str.__contains__('**foo**', 'foo')
'True' 되돌려줍니다. 이 초끈 인스턴스입니다 에서 이 함수를 호출하는 수도 있습니다.
'**foo**'.__contains__('foo')
그러나 don& # 39, t. 의미상 밑줄로 시작하는 메서드입니다 간주됩니다 보면안돼. 이 때 사용할 수 있는 단 하나의 이유는 '에서' 와 '없는' 확장 기능 (예를 들면 만약 하위 클래스화 '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
다른 언어로 시험 방법, 그래서 당신은 할 수 없는 이 두 가지 방법을 사용하여 직접 서브문자열을 갖추고 있지만, 파이썬, 것이 훨씬 더 효율적으로 사용할 수 있는 '에서' 비교 연산자.
같은 목표를 달성하기 다양한 방법을 비교할 수 있습니다.
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'))),
}
그리고 지금 우리가 지켜보리니 '다른' 에서 사용하는 것보다 훨씬 빠릅니다. 짧은 시간에 avamer 작업을 수행하는 데 좋다.
>>> 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}
<!
누구나 좋아하는 다타비츠. # 39 을 사용하여 here& 한 마리의 및 매플로리브:
import pandas
import matplotlib.pyplot as plt
s = pandas.Series(list(perf_dict.values()), index=list(perf_dict.keys()))
s.plot('bar')
plt.show()
다음은 몇 가지 유용한 참조용이므로 스스로 말을 할 수 있는 것과 관련해 '에서' 방법:
"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
단서 조항. '방법' 이 아니라, 그 목록은 이트라블레스 써줬지 이트라블레스 관한 행위
만족하고 경우 '" blah"; 그런데 그걸 할 수 있는 섬슬링 함수 / 메서드 호출, 이렇게 할 수 있을 것입니다
import operator
if not operator.contains(somestring, "blah"):
continue
파이썬 늘리거나 줄일 수 있는 모든 사업자의 [작동자 모듈에서는] [1] '에서' 등.
[1]: https://docs.python.org/3.5/library/operator.html # 오페라토리콘테인스
() '' 이스카운트 사용할 수 있습니다.
이 정수 값 반환되므로 횟수를 서브노드 구체화하십시오 나타나는 구체화하십시오.
예를 들면 다음과 같습니다.
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