详解python中index()、find()方法
作者:foremostxiao 发布时间:2021-02-25 02:38:59
标签:python,index(),find()
python中index()、find()方法,具体内容如下:
index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。影响后面程序执行
index()方法语法:str.index(str, beg=0, end=len(string))
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
str1='python is on the way']
str2='on'
#空格,等其他操作符对其索引位置也有影响
#在str1中检测字符串中是否含有子字符串str2 str1.index(str2,beg=0,end=len(str1))
#如果包含子字符串 返回检测到的索引值
print(str1.index(str2))
#从索引1开始检测,检测长度为3
print(str1.index(str2,1,3))
如果包含子字符串返回开始的索引值,否则抛出异常。
user_name = ['xiaolei','xiaoman','lixia']
pass_word = ['123','456','789']
username = input('username:').strip()
password = input('password:').strip()
if username in user_name and password == pass_word[user_name.index(username)]:
print(f"登录成功,欢迎您:{username}")
else:
print("错误!")
若输入:username == xiaolei
user_name.index(username) == 0
所以:password == pass_word[0] == 123
Python find()方法,不能用于列表list
str.find(str, beg=0, end=len(string))
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。不影响后面程序执行
str1='python is on the way'
str2='on'
str3='nice'
print(str1.index(str2))
#不在字符串str1中
print(str1.find(str3))
#从索引1开始检测,检测长度为3
print(str1.find(str2,1,3))
运行结果:
知识点补充:Python将DataFrame的某一列作为index
下面代码实现了将df中的column列作为index
df.set_index(["Column"], inplace=True)
总结
以上所述是小编给大家介绍的python中index()、find()方法,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.cnblogs.com/foremostxl/p/9394437.html
0
投稿
猜你喜欢
- 最近工作中刚好要清洗一批客户数据,涉及到身份证号码15位和18位的转换,特意研究了下,在这里分享下。身份证号码的构成既然谈到了身
- 淡入淡出图片轮换轮播效果,可以做新闻图片推荐需要的拿去用,效果预览请点击运行代码相关效果推荐:迅雷首页新闻图片轮播效果js源码 <!D
- MySQL 8.0.28引入新功能MySQL 8.0.28开始,新增一个特性,支持监控统计并限制各个连接(会话)的内存消耗,避免大量用户连接
- 简介现在的网站没有 HTTPS 都不好意思见人了.超文本传输安全协议(英语:HyperText Transfer Protocol Secu
- 【OpenCV】⚠️高手勿入! 半小时学会基本操作⚠️图像处理概述OpenCV 是一个跨平台的计算机视觉库, 支持多语言, 功能强大. 今天
- 今天遇到一个问题,要保证页面渲染前请求的数据已经得到了由于user是在异步请求之后保存在session中,而在页面渲染时session中还没
- 遇到这样一个需求,有一张表,要给这张表新增一个字段delta,delta的值等于每行的c1列的值减去上一行c1列的值。我的解决方案,可以通过
- 清除浮动一个凡是做页面的人都会遇到的一个东西,但是是否大家都能够清楚的知道,全方位的了解呢?于是一闲下来了马上写了这样的一篇文章,不能讲面面
- 本文实例讲述了JS实现屏蔽网页右键复制及ctrl+c复制的方法。分享给大家供大家参考,具体如下:老是有些网站会屏蔽你的鼠标右键或者用快捷键复
- <html> <head> <script type="text/javascript"&
- 1 准备工作1.1 环境搭建1.1.1 安装python3.6python安装官网1.1.2 安装django2.2pip install
- 使用了application及结合数据库来保存统计数据 <html><head><title>
- 平时工作过程中,git在push代码的时候有时会遇到如下的错误错误原因文件冲突,本地的代码和远程Repository中的文件个数不一致(即远
- 网页兼容测试,除了做不同浏览器的兼容测试,还要观察网页在不同分辨率下的表现情况。在页面中使用了CSS绝对定位,发现在宽屏下错位。随后测试非1
- Francesc (@francesc) 是 Go 核心团队的一员, 是提倡 Google Cloud 平台的开发者. 他是一个编程语言的爱
- 想弄个截屏工具,整理一下学生错题什么的,原来用的方法是:先运行QQ,再监听键盘热键(“ctrl+alt+a”)。后来发现有些问题:需要先上Q
- 搭建python环境1.百度搜索python3.7下载,找到官网下载安装包,运行安装包并配置环境变量。2.这里一定要安装python3.7版
- 一、基本使用最近研究了一下 el-upload组件 踩了一些小坑 写起来大家学习一下很经常的一件事情 经常会去直接拷贝 elem
- 共享标签默认情况下,git push 命令并不会传送标签到远程仓库服务器上。在创建完标签后,你必须显式地(手动)推送标签到远程服务
- 大家好,本期给大家带来Python字典11个方法的全面解析,希望对你有所帮助。字典(Dictionary)是Python提供的一种常用的数据