我正在寻找一个 string.contains
要么 string.indexof
Python中的方法。
我想要做:
if not somestring.contains("blah"):
continue
我正在寻找一个 string.contains
要么 string.indexof
Python中的方法。
我想要做:
if not somestring.contains("blah"):
continue
你可以使用 in
操作者:
if "blah" not in somestring:
continue
如果它只是一个子串搜索,你可以使用 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
。这可能是也可能不是你想要的。
if needle in haystack:
是正常的用法,正如@Michael所说 - 它依赖于 in
运算符,比方法调用更可读,更快。
如果你真的需要一个方法而不是一个操作符(例如做一些奇怪的事情 key=
对于一种非常特殊的......?),那就是 'haystack'.__contains__
。但是因为你的例子是用于 if
,我猜你真的不是说你说的话;-)。直接使用特殊方法不是好形式(也不可读,也不高效) - 而是通过委托给它们的运算符和内置函数来使用它们。
基本上,您希望在python中的字符串中查找子字符串。有两种方法可以在Python中搜索字符串中的子字符串。
方法1: in
操作者
你可以使用Python in
运算符检查子字符串。它非常简单直观。它会回来 True
如果在字符串else中找到子字符串 False
。
>>> "King" in "King's landing"
True
>>> "Jon Snow" in "King's landing"
False
方法2: str.find()
方法
第二种方法是使用 str.find()
方法。在这里,我们称之为 .find()
在要找到子字符串的字符串上的方法。我们将子字符串传递给find()方法并检查其返回值。如果其值不是-1,则在字符串中找到子字符串,否则不会。返回的值是找到子字符串的索引。
>>> some_string = "valar morghulis"
>>> some_string.find("morghulis")
6
>>> some_string.find("dohaeris")
-1
我建议你使用第一种方法,因为它更Pythonic和直观。
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}
不,没有 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
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
使用布尔返回值查找字符串是否包含几个字符的另一种方法(即 True
或者“错误”:
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