
在程序的开发中,检查一个字符串是否包含一个子串,是常用的功能。Python 提供了很多的方法来完成查找子串的功能。最简单有快速的方法是使用 “in” 操作符 , 它作为比较操作符来使用。其他的Python方法,如find(), index(), count() 等等,也可以完成这个功能。
使用Python的”in”操作符
这是最简单并且最快的方法,如果包含则返回true,否则返回 false。
str=”Hello, World!”
print(“World” in str)
输出
True
Python的 “in” 操作符有两个参数,一左一右,检查右边的字符串是否包含左边的字符串。
更多的 “in” 操作符的例子
>>>str=”Hello,World!”
>>>”WORLD” in str
False
>>>”world” in str
False
>>>”python” in str
False
>>>”Hello” in str
True
注意: “in”操作符是区分大小写的。
__contains__() 函数
Python 字符串类有 __contains__() 方法 ,可以用它来检查子串的包含。实际上,当我们使用 “in”操作符的时候,系统调用的就是 __contains__()函数。 __contains__ 方法以下划线开头,表达的是私有,所以不建议使用它,使用 in操作符的可读性更强。
使用Python的 str.find() 方法
另外的是 string.find() 方法 。find()方法检查是否包含,并且返回子串在原字符串中的索引的位置,如果不包含,返回 -1。
str=”Hello, World!”
if str.find(“World”)!=-1:
print(“Found the string”)
else:
print(“Not found!!!”)
输出
Found the string
更多find()方法的例子
>>>str=”Hello, World!”
>>>str.find(“World”)
7
>>>str.find(“python”)
-1
>>>str.find(“WORLD”)
-1
>>>str.find(“Hello”)
0
str.find()方法 很少使用, 容易混淆 ,但是仍是有效的方法。
使用Python 正则表达式
正则表达式作为模式匹配被广泛使用。 Python 有内建的包 re , 它用来完成正则表达式的功能。 re 模块包含函数 search() , 它可以实现特定模式的匹配查找。re.search(pattern, string, flags[optional])
例子
from re import search
str=”Hello, World!”
substring = “tack”
if search(“World”, str):
print (“Substring Found!”)
else:
print (“Not found!”)
输出
Substring Found!
使用str.count()方法
如果想统计子串在原字符串里面出现的次数,可以使用 count() 方法 。如果不包含,则返回0。
>>>str=”Hello, World!”
>>>str.count(“World”)
1
>>>str. count (“python”)
0
>>>str. count (“WORLD”)
0
>>>str. count (“Hello”)
1
Python 基础