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

in

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

find

string = 'hello world'
if string.find('world') == 6:  # 6的意思是world字符从哪个序开始,因为w位于第6个,即序为6
    print 'Exist'
else:
    print 'Not exist'

index

此方法与find作用类似,也是找到字符起始的序号。如果没找到,程序会抛出异常

string = 'hello world'
if string.index('world') > -1:  # 因为-1的意思代表没有找到字符,所以判断>-1就代表可以找到
    print 'Exist'
上一篇 Python格式化千分位数字
下一篇 Python编码和解码JSON对象
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。