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

  • 第一种方法:in

string = 'helloworld'

if 'world' in string:

  print 'Exist'

else:

  print 'Not exist'
View Code
  • 第二种方法:find

1 string = 'helloworld'
2 
3 if string.find(’world‘) == 5: #5的意思是world字符从那个序开始,因为w位于第六个,及序为5,所以判断5
4 
5   print 'Exist'
6 
7 else:
8 
9   print 'Not exist'
View Code
  • 第三种方法:index,此方法与find作用类似,也是找到字符起始的序号

1 if string.index(’world‘) > -1: #因为-1的意思代表没有找到字符,所以判断>-1就代表能找到
2 
3   print 'Exist'
4 
5 else:
6 
7   print 'Not exist'
View Code
原文地址:https://www.cnblogs.com/njuptlwh/p/7488152.html