python字符串截取 - python字符串方法
Python有一个字符串'contains'substring方法吗? (10)
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
comparison运算符会更有效。
性能比较
我们可以比较实现相同目标的各种方式。
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}
我正在寻找Python中的string.contains
或string.indexof
方法。
我想要做:
if not somestring.contains("blah"):
continue
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
方法作用于迭代,而不仅仅是字符串。
不,没有任何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 ]
使用布尔返回值(即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
基本上,您希望在python中的字符串中查找子字符串。 有两种方法可以在Python中搜索字符串中的子字符串。
方法1: in
运营商中
您可以使用Python的in
运算符来检查子字符串。 它非常简单直观。 如果在字符串中找到子字符串,则返回True
,否则返回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和直观。
如果你"blah" in somestring
感到满意,但希望它是一个函数调用,你可以这样做
import operator
if not operator.contains(somestring, "blah"):
continue
Python中的所有运算符都可以或多或少地在运算符模块中找到,包括。
如果您正在寻找对整个单词不区分大小写的搜索,而不是另一个单词中包含的子字符串:
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
您可以使用in
运算符 :
if "blah" not in somestring:
continue
显然,对于矢量方式的比较,没有类似的东西。 一种明显的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
这是你的答案:
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