python 判断字符串是否包含子字符串

第一种方法:in,主要是利用对象判断code

string = 'helloworld'

if 'world' in string:
  print 'Exist'
else:
  print 'Not exist'

第二种方法:find对象

string = 'helloworld'
if string.find(’world‘) == 5: #5的意思是world字符从那个序开始,由于w位于第六个,及序为5,因此判断5
  print 'Exist'
else:
  print 'Not exist'

第三种方法:index,此方法与find做用相似,也是找到字符起始的序号string

if string.index(’world‘) > -1: #由于-1的意思表明没有找到字符,因此判断>-1就表明能找到
  print 'Exist'

若是没找到,程序会抛出异常程序

相关文章
相关标签/搜索