Python String index() function returns the lowest index where the specified substring is found. If the substring is not found then ValueError is raised.

Python String index()函数返回找到指定子字符串的最低索引。 如果未找到子字符串,则引发ValueError

Python字符串index()语法 (Python String index() syntax)

This function syntax is:

该函数语法为:

str.index(sub[, start[, end]])

The start parameter default value is 0 and it’s an optional argument.

起始参数的默认值为0,它是一个可选参数。

The end argument default value is length of the string, it’s an optional argument.

end参数的默认值是字符串的长度,它是一个可选参数。

We should use the index() function when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.

当我们想知道子字符串的索引位置时,应该使用index()函数。 为了检查是否存在子字符串,我们可以使用in运算符。

Python字符串索引()与查找() (Python string index() vs find())

Python string index() function raises ValueError if substring is not found whereas find() function returns -1. This is the only difference between these functions.

如果未找到子字符串,Python字符串index()函数将引发ValueError,而find()函数将返回-1。 这是这些功能之间的唯一区别。

Python String index()示例 (Python String index() examples)

Let’s look at some simple examples of index() function.

让我们看一下index()函数的一些简单示例。

s = 'abcd1234dcba'print(s.index('a'))
print(s.index('cd'))
print(s.index('1', 0, 5))

Output:

输出:

0
2
4

Now let’s look at another example where the substring is not present and ValueError is thrown. I will use a try-except block to catch the exception and print its message.

现在让我们看另一个不存在子字符串并且引发ValueError的示例。 我将使用try-except块来捕获异常并打印其消息。

s = 'abcd1234dcba'try:print(s.index('1', 0, 2))
except ValueError as ve:print(ve)

Output: substring not found

输出: substring not found

Python字符串rindex() (Python String rindex())

Python string rindex() method is similar to index(), except that search is performed from right to left.

Python字符串rindex()方法类似于index(),不同之处在于搜索是从右到左执行的。

s = 'abcd1234dcba'print(s.rindex('a'))
print(s.rindex('cd'))
print(s.rindex('1', 0, 5))try:print(s.rindex('1', 0, 2))
except ValueError as ve:print(f'Error Message = {ve}')

Output:

输出:

11
2
4
Error Message = substring not found

使用index()查找子字符串的所有索引 (Find all indexes for substring using index())

Python string index() method returns the first matched index. We can define a custom function to find all the indexes where the substring is found.

Python字符串index()方法返回第一个匹配的索引。 我们可以定义一个自定义函数,以查找找到子字符串的所有索引。

def find_all_indexes(input_str, search_str):l1 = []length = len(input_str)position = 0while position < length:try:i = input_str.index(search_str, position)l1.append(i)position = i + 1except ValueError as ve1:# finally exception will be raised because all the indexes are foundreturn l1s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))

Output:

输出:

[0, 2, 3, 6, 7, 10, 11]
[2, 6, 10]
GitHub Repository.GitHub存储库中检出Python脚本和更多字符串示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/23992/python-string-index

Python字符串index()相关推荐

  1. “Python字符串index()方法应用案例”文末三道思考题答案

    问题链接:Python字符串index()方法应用案例一则 本文给出上文文末三个思考题的参考答案,当然,这些答案不是唯一的,也不是最高效的,只是演示字符串方法和内置函数的用法,并且在原题代码上做最少的 ...

  2. Python字符串index()方法应用案例一则

    问题描述:查找字符串中每个字符第一次出现的位置. 技术要点:字符串的index()方法返回指定子串在当前字符串中首次出现的位置. 参考代码与运行结果: 思考题: 1.如果要查找每个字符最后一次出现的位 ...

  3. 真香!精心整理了 100+Python 字符串常用操作

    来源丨萝卜大杂烩 作者丨周萝卜 字符串作为平时使用最多的数据类型,其常用的操作我们还是很有必要熟记于心的,本文整理了多种字符串的操作的案例,还是非常用心,记得点赞收藏~ 字符串切片操作 test = ...

  4. python字符串find函数-python字符串查找函数的用法详解

    python字符串查找函数的使用 打开Python开发工具IDLE,新建"findstr.py'文件,并写代码如下: s ='/ab/bx,.s' print (s.find('/x')) ...

  5. python字符串find函数-Python内置的字符串处理函数整理

    str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str) 例:print '%s length ...

  6. python字符串操作_浅谈Python 字符串特有的操作方法

    来源:(微信号:python_cat)" 正如<你真的知道Python的字符串是什么吗?>所写,Python中字符串是由Uniocde编码的字符组成的不可变序列,它具备与其它序列 ...

  7. Python 字符串方法详解

    Python 字符串方法详解 本文最初发表于赖勇浩(恋花蝶)的博客(http://blog.csdn.net/lanphaday),如蒙转载,敬请保留全文完整,切勿去除本声明和作者信息. 在编程中,几 ...

  8. python字符串解释_Python学习:字符串的简单解释,深入浅出

    字符串是python很常见的一种数据类型,比如日志的打印,程序中函数的注释,数据库的访问,变量的操作都需要用到字符串. 一.字符串基础 字符串是由独立字符组成的一个序列,通常包含在单引号('')双引号 ...

  9. python字符串之查找与替换_Python字符串操作(查找,替换,分割和连接)方法及其使用...

    str 提供了如下常用的执行查找.替换等操作的方法: startswith():判断字符串是否以指定子串开头. endswith():判断字符串是否以指定子串结尾. find():查找指定子串在字符串 ...

最新文章

  1. Python OpenCV应用K均值聚类进行颜色量化
  2. Dynamics 365 for CRM: Sitemap站点图的可视化编辑功能
  3. webstorm 配置 babel
  4. (转)Vix_API 操作 VMware
  5. 拋棄虛擬機,微軟實驗讓我們在線做(二)
  6. 吐司面包的做法_无糖粗粮吐司面包的做法+配方,超柔超软,一次发酵
  7. 第十一届蓝桥杯大赛软件赛省赛第二场 C/C++ 大学B组
  8. 用Delphi进行word开发
  9. 外联接、自联接与联合
  10. PyCharm集成Anaconda3环境下安装 腾讯优图报错 ERROR: Could not install packages due to an EnvironmentError
  11. 无限网盘,36个T,360网盘无限空间的申请方法www.credream.com
  12. elasticsearch_head插件安装
  13. Bzoj4480: [Jsoi2013]快乐的jyy 广义后缀自动机 倍增 哈希 manacher
  14. 和opengl的关系_从零开始的图形学学习(零):一切的开始 —— 自建OpenGL开发框架...
  15. 扫雷游戏代码+代码分析
  16. 计算机折线图教程,excel怎么插入折线图 excel怎么将多个折线图合并
  17. My97DatePicker时间控件在asp.net的应用
  18. android cts问题分析,一则CTS测试错误分析
  19. 寻声定位 matlab,春天里的小情趣
  20. 关于解决Mac上keras数据集自动下载过慢问题(不要问我是怎么知道的,干就完了,奥利给!)

热门文章

  1. base,override,virtual
  2. [转载] Python - filter()用法
  3. [转载] Python中endswith() 函数法用于判断字符串是否以指定后缀结尾
  4. [转载] 卷积神经网络做mnist数据集识别
  5. [转载] Python图结构(复杂网络)可视化模块——networkx
  6. SPI通信实验---verilog(FPGA作为从机,使用可读可写)
  7. tornado框架基础05-模板继承、UImodul和UImethods
  8. 总结下MySql优化。防止数据灾难的发生。
  9. (25)软件工程开发规范
  10. 启动Samples-Web-Start Web Server时,提示Could not open port 1080