Python有一个字符串’contains’子串方法吗?
我正在寻找Python中的一个string.contains
或string.indexof
方法.
我想要做:
if not somestring.contains("blah"):
continue
回答
您可以使用in
运营商:
if "blah" not in somestring:
continue
- 在引擎盖下,Python将按顺序使用`__contains __(self,item)`,`__iter __(self)`和`__getitem __(self,key)`来确定项是否位于给定的包含中.实现至少一种方法,使`in`可用于您的自定义类型.
- 只要确保somestring不是None.否则你得到一个'TypeError:类型为'NoneType'的参数不可迭代`
- @SamChats 参见 /sf/ask/1269776231/ 了解实现细节(在 CPython 中;afaik 语言规范不强制要求任何特定算法这里)。
- FWIW,这是达成上述目标的惯用方式。
- 对于字符串,Python`in`运算符是否使用Rabin-Carp算法?
- This Python overload of `in` for strings looks a tad inconsistent and ugly to me (although undoubtly practical) as I'm used to interpret "in" as "is an element of" and that breaks here -- compare `"blah" in mystring` with `"blah" in list(mystring)` ...
- 这在像“.so”这样的代码中是不一致和丑陋的。在文件名或文件名.endswith(".blah")`中。
- @Kaz应该很丑,因为您在错误的抽象级别上进行思考。另一方面,filepath.suffixes中的“ .so”非常漂亮,并明确说明了您真正想做的事情。
如果它只是一个子串搜索,你可以使用string.find("substring")
.
你必须与小心一点find
,index
和in
虽然,因为它们是字符串搜索.换句话说,这个:
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
.这可能是也可能不是你想要的.
- @aaronasterling明显可能,但不完全正确.如果您有标点符号或者它在开头或结尾怎么办?资本化怎么样?更好的是不区分大小写的正则表达式搜索` bisb`(单词边界).
- +1用于突出显示子字符串搜索中涉及的陷阱.显而易见的解决方案是`if'是'在s:`中,它将返回`False`,因为它可能是预期的.
- `'是'不在(w.lower()中用于s.translate中的w(string.maketrans(''*len(string.punctuation + string.whitespace),string.punctuation + string.whitespace)).split() ` - 好的,点了.现在这太荒谬了......
- @JamieBull:我非常怀疑使用`s.split(string.punctuation + string.whitespace)`的任何实际输入拆分都会拆分一次; `split`与`strip` /`rstrip` /`lstrip`系列函数不同,只有当它按照确切的顺序连续看到所有的分隔符时才会分裂.如果你想拆分字符类,你就会回到正则表达式(此时,搜索`r' bisb'`而不进行拆分是更简单,更快捷的方法).
- @JamieBull再一次,您必须考虑是否要将标点符号作为单词的分隔符.分裂与检查"是"的天真解决方案大致相同,特别是,它不会捕获"这是,逗号"或"它是".
if needle in haystack:
是正常的用法,正如@Michael所说 - 它依赖于in
运算符,比方法调用更具可读性和更快速度.
如果你真的需要一个方法而不是一个操作符(例如,做一些奇怪key=
的非常奇怪的类型......?),那就是'haystack'.__contains__
.但是因为你的例子是用于一个if
,我想你并不真正意味着你所说的;-).直接使用特殊方法不是好形式(也不可读,也不高效) - 而是通过委托给它们的运算符和内置函数来使用它们.
Python有一个字符串包含substring方法吗?
是的,但是Python有一个比较运算符,你应该使用它,因为语言意图使用它,而其他程序员则希望你使用它.该关键字是in
,用作比较运算符:
>>> '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')
但不要.以下划线开头的方法在语义上被认为是私有的.使用它的唯一原因是扩展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时,使用in
比较运算符会更有效.
性能比较
我们可以比较实现相同目标的各种方式.
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}
- 为什么要避免使用`str.index`和`str.find`?你怎么建议有人找到子串的索引而不是它是否存在?(或者你的意思是避免使用它们代替包含 - 所以不要使用`s.find(ss)!= -1`而不是s`中的`s?)
- 确切地说,尽管通过优雅使用"re"模块可以更好地解决使用这些方法背后的意图.我还没有在我编写的任何代码中找到str.index或str.find的用法.
in
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
警告.列表是可迭代的,并且该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
如果你满意"blah" in somestring
但希望它是一个函数调用,你可以这样做
import operator
if not operator.contains(somestring, "blah"):
continue
Python中的所有运算符都可以或多或少地在运算符模块中找到,包括in
.
您可以使用以下几种方法:
y.count()
y.count()
y.count()
1是布尔表达式,意味着它将返回状态True of False,具体取决于条件是否满足.
例如:
string.count("bah") >> 0
string.count("Hello") >> 1
string.count("bah") >> 0
string.count("Hello") >> 1
string.count("bah") >> 0
string.count("Hello") >> 1
2将返回子字符串在字符串中出现的次数的整数值.
例如:
3将返回给定子字符串初始位置的索引值.如果找不到子字符串,这也将返回-1.
例如:
- 没有。我的观点是“为什么要回答与9年前其他人完全相同的事情”?
- 因为我正在审核网站...我已经在meta https://meta.stackoverflow.com/questions/385063/popular-question-answers-cleanup上提问了
- 当您只想_check_是否存在时,对字符串进行计数非常昂贵...
- Shifting right is almost certainly not what you want to do here.
- 自2010年以来的原始帖子中存在的方法,因此我最终在社区的一致同意下对其进行了编辑(请参阅元帖子https://meta.stackoverflow.com/questions/385063/popular-question-answers-cleanup)
- 然后,如果您有权删除它,则删除它,否则执行您必须执行的操作并继续。海事组织,这个答案增加了价值,这反映在用户的赞成票上。
这是你的答案:
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', ' ', ' ']