python判断字符串(string)是否包含(contains)子字符串的方法

python判断字符串(string)是否包含(contains)子字符串的方法

python的string对象没有contains方法,不用使用string.contains的方法判断是否包含子字符串,但是python有更简单的方法来替换contains函数。

方法1:使用 in 方法实现contains的功能:

site = 'http://www.sharejs.com/' if "sharejs" in site: PRint('site contains sharejs')

输出结果:site contains sharejs

方法2:使用find函数实现contains的功能。

s = "This be a string" if s.find("is") == -1: print "No 'is' here!" else: print "Found 'is' in the string."

输出结果:No ‘is’ here!