Skip to content

Latest commit

 

History

History
36 lines (21 loc) · 1000 Bytes

File metadata and controls

36 lines (21 loc) · 1000 Bytes

#判断一个字符串是否含子串的方法

原问题地址:http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method

##问题:

我在Python中查找string.containsstring.indexof方法。

我想实现:

if not somestring.contains("blah"):
    continue

##回答 1:

你可以使用in

if "blah" not in somestring: 
    continue

##回答 2:

如果你只是搜索一个子字符串,可以使用string.find("substring")

然而,你使用findindexin的时候一定要小心一点,因为这是在搜索子字符串。换句话说,下面的内容:

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:

这可能是你想要的,也可能不是。