【发布时间】:2022-01-13 21:06:08
【问题描述】:
我正在寻找 Python 中的 string.contains 或 string.indexof 方法。
我想做:
if not somestring.contains("blah"):
continue
【问题讨论】:
标签: python string substring contains
我正在寻找 Python 中的 string.contains 或 string.indexof 方法。
我想做:
if not somestring.contains("blah"):
continue
【问题讨论】:
标签: python string substring contains
您可以使用in operator:
if "blah" not in somestring:
continue
【讨论】:
__contains__(self, item)、__iter__(self) 和__getitem__(self, key) 来确定项目是否位于给定的包含中。至少实现其中一种方法以使 in 可用于您的自定义类型。
TypeError: argument of type 'NoneType' is not iterable
in 运算符是否使用 Rabin-Carp 算法?
【讨论】:
if ' is ' in s:,它将按(可能)预期返回False。
\bis\b(单词边界)进行不区分大小写的正则表达式搜索。
Python 有没有字符串包含子字符串的方法?
99% 的用例将使用关键字in 覆盖,该关键字返回True 或False:
'substring' in any_string
对于获取索引的用例,使用str.find(失败时返回-1,并且具有可选的位置参数):
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比较运算符,因为
>>> '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 和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 虚拟机调用 - 这应该足以解释差异。
【讨论】:
str.index 和str.find?您还会如何建议某人找到子字符串的索引,而不仅仅是它是否存在? (或者您的意思是避免使用它们代替 contains - 所以不要使用 s.find(ss) != -1 而不是 ss in s?)
re 模块来更好地解决。我还没有在我编写的任何代码中找到 str.index 或 str.find 的用途。
str.count 的建议 (string.count(something) != 0)。 颤抖
if needle in haystack: 是正常使用,正如@Michael 所说——它依赖于in 运算符,比方法调用更具可读性和速度。
如果你真的需要一个方法而不是一个操作符(例如,做一些奇怪的key= 来进行非常特殊的排序...?),那就是'haystack'.__contains__。但是由于您的示例用于if,我猜您并不是真的想说什么;-)。直接使用特殊方法不是很好的形式(既不可读,也不高效)——它们应该通过委托给它们的操作符和内置函数来使用。
【讨论】:
inPython 字符串和列表以下是一些关于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 中的所有运算符或多或少都可以在operator module 中找到,包括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
【讨论】:
in 不应该与列表一起使用毫无意义,因为它对元素进行线性扫描并且比较慢。请改用集合,尤其是在要重复进行成员资格测试时。
您可以使用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', ' ', ' ']
【讨论】: