linqy的个人博客分享 http://blog.sciencenet.cn/u/linqy

博文

python 查看字符串是否包含某个特定的子字符串

已有 3713 次阅读 2019-8-6 14:54 |系统分类:科研笔记| python

一共有三个方法可以使用,下面分别举例说明

第一种方法:in

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作用类似,也是找到字符起始的序号

            if string.index(’world‘) > -1: #因为-1的意思代表没有找到字符,所以判断>-1就代表能找到

              print 'Exist'

建议使用第一种方法

因为第二种和第三种,在查询不到时候,容易出错,程序会抛出异常

参考:https://www.cnblogs.com/wq242424/p/6524697.html



https://blog.sciencenet.cn/blog-3134052-1192658.html

上一篇:dell笔记本插入耳机仍有外因的原因
下一篇:[转载]ARCGIS 检查数据的岛洞问题
收藏 IP: 112.53.64.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-24 09:08

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部