在Python中查找字符串中子字符串索引的5种方法 (5 Ways to Find the Index of a Substring in Strings in Python)

  1. str.find()

    str.find()

  2. str.rfind()

    str.rfind()

  3. str.index()

    str.index()

  4. str.rindex()

    str.rindex()

  5. re.search()

    re.search()

str.find() (str.find())

str.find() returns the lowest index in the string where the substring sub is found within the slice s[start:end]. It returns -1 if the sub is not found.start and end are optional arguments.

str.find()返回在切片s[start:end]找到子字符串sub的字符串中的最低索引。 如果找不到该子项,则返回-1startend是可选参数。

str.find(sub,start,end)

例子1.使用str.find()方法 (Example 1. Using str.find() method)

Photo by the author
作者照片

The string is banana.

线是banana

The substring is an.

该子是an

The substring occurs two times in the string.

子字符串在字符串中出现两次。

str.find(“an”) returns the lowest index of the substring an.

str.find(“an”)返回子字符串an的最低索引。

s1="banana"print (s1.find("an"))#Output:1

例子2.使用str.find()方法和提到的start参数 (Example 2. Using str.find() method with the start parameter mentioned)

The substring is an.

该子是an

The start parameter is 2. It will start searching the substring an from index 2.

起始参数为2 。 它将开始从索引2搜索子字符串an

s1="banana"print (s1.find("an",2))#Output:3

例子3.如果没有找到子字符串,它将返回-1 (Example 3. If the substring is not found, it will return -1)

The substring is ba.

子字符串是ba

The start parameter is 1 and the stop parameter is 5. It will start searching the substring from index 1 to index 5 (excluded).

起始参数为1 ,终止参数为5 。 它将开始搜索从索引1到索引5(不包括)的子字符串。

Since the substring is not found in the string within the given index, it returns -1.

由于在给定索引的字符串中找不到子字符串,因此它返回-1

s1="banana"print (s1.find("ba",1,5))#Output:-1

2. str.rfind() (2. str.rfind())

str.rfind() returns the highest index in the string where the substring sub is found within the slice s[start:end]. It returns -1 if the sub is not found.start and end are optional arguments.

str.rfind()返回在slice s[start:end]找到子字符串sub的字符串中的最高索引。 如果找不到该子项,则返回-1startend是可选参数。

str.rfind(sub,start,end)

例子1.使用str.rfind()方法 (Example 1. Using str.rfind() method)

Photo by the author
作者照片

The string is banana.

线是banana

The substring is an.

该子是an

The substring occurs two times in the string.

子字符串在字符串中出现两次。

str.find(“an”) returns the highest index of the substring an.

str.find(“an”)返回子字符串an的最高索引。

s1="banana"print (s1.rfind("an"))#Output:3

例子2.使用str.rfind()方法并提到开始和结束参数 (Example 2. Using str.rfind() method with the start and end parameters mentioned)

The substring is an.

该子是an

The start and end parameters are 1 and 4, respectively. It will start searching the substring from index 1 and index 4 (excluded).

startend参数分别为14 。 它将开始从索引1和索引4(排除)中搜索子字符串。

s1="banana"print (s1.rfind("an",1,4))#Output:1

例子3.如果没有找到子字符串,它将返回-1 (Example 3. If the substring is not found, it will return -1)

The substring is no.

子字符串为no

Since the substring is not found in the string, it returns -1.

由于在字符串中找不到子字符串,因此它返回-1

s1="banana"print (s1.rfind("no"))#Output:-1

3. str.index() (3. str.index())

Similarly to find(), str.index() returns the lowest index of the substring found in the string. It raises a ValueError when the substring is not found.

find()类似, str.index()返回 字符串中找到的子字符串的最低索引。 当找不到子字符串时,它将引发ValueError

例子1.使用str.index()方法 (Example 1. Using str.index() method)

s1="banana"print (s1.index("an"))#Output:1

例子2.在给定start和end参数的情况下使用str.index()方法 (Example 2. Using str.index() method with the start and end parameters given)

s1="banana"print (s1.index("an",2,6))#Output:3

例子3.如果没有找到子字符串,它将引发一个ValueError (Example 3. If the substring is not found, it raises a ValueError)

s1="banana"print (s1.index("no"))#Output:ValueError: substring not found

4. str.rindex() (4. str.rindex())

Similarly to find(), str.rindex() returns the highest index of the substring found in the string. It raises a ValueError when the substring is not found.

find()类似, str.rindex()返回在字符串中找到的子字符串的最高索引。 当找不到子字符串时,它将引发ValueError

例子1.使用str.rindex()方法 (Example 1. Using str.rindex() method)

s1="banana"print (s1.rindex("an"))#Output:3

例子2.在给定start和end参数的情况下使用str.index()方法 (Example 2. Using str.index() method with the start and end parameters given)

s1="banana"print (s1.rindex("an",0,4))#Output:1

例子3.如果没有找到子字符串,它将引发一个ValueError (Example 3. If the substring is not found, it raises a ValueError)

s1="banana"print (s1.rindex("no"))#Output:ValueError: substring not found

5. re.search() (5. re.search())

re.search(pattern, string, flags=0)

“Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.” — Python’s official documentation

“扫描字符串以查找正则表达式模式产生匹配项的第一个位置,然后返回相应的匹配对象。 如果字符串中没有位置与模式匹配,则返回None否则,返回None 。 请注意,这不同于在字符串中的某个位置找到零长度匹配。” — Python的官方文档

  • re.search (pattern, string): We have to mention the pattern to be searched in the string.

    re.search (模式,字符串):我们不得不提一下pattern中要搜索string

  • The return type matches the object that contains the starting and ending index of that pattern (substring).返回类型与包含该模式(子字符串)的开始和结束索引的对象匹配。
  • We can find the start and end indices from the match object using match.start() and match.end().

    我们可以使用match.start()match.end()从match对象中找到startend索引。

Match.start([group])Match.end([group])

“Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match.” — Python’s documentation

“返回分组匹配的子字符串的开始和结束的索引; 默认为零(表示整个匹配的子字符串)。 如果存在但没有参与比赛,则返回-1 。” — Python的文档

  • We can get the start and end indices in tuple format using match.span().

    我们可以使用match.span()获得元组格式的startend索引。

Match.span([group])

“For a match m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). group defaults to zero, the entire match.” — Python’s documentation

“对于匹配项m ,返回2元组(m.start(group), m.end(group)) 。 请注意,如果group对匹配没有贡献,则为(-1, -1)默认为零,即整个匹配。” — Python的文档

例子1.使用re.search() (Example 1. Using re.search())

示例2.如果在字符串中未找到子字符串,则返回None (Example 2. If a substring is not found in the string, it returns None)

import restring = 'banana'pattern = 'no'match=(re.search(pattern, string))#Returns match objectprint (match)#Output: None

结论 (Conclusion)

  • Python 3.8.1 is used.使用Python 3.8.1。
  • str.find(), str.rfind() — Returns -1 when a substring is not found.

    str.find()str.rfind() —在找不到子字符串时返回-1

  • str.index(),str.rindex() — Raises a ValueError when a substring is not found.

    str.index()str.rindex() —在找不到子字符串时引发ValueError

  • re.search() — Returns None when a substring is not found.

    re.search() —如果找不到子字符串,则返回None

  • str.find(), str,index() — Returns the lowest index of the substring.

    str.find()str,index() —返回子字符串的最低索引。

  • str.rfind(), str.rindex() — Returns the highest index of the substring.

    str.rfind()str.rindex() —返回子字符串的最高索引。

  • re.search() — Returns the match object that contains the starting and ending indices of the substring.

    re.search() —返回包含子字符串的开始和结束索引的匹配对象。

资源(Python文档) (Resources (Python Documentation))

  • str.find

    查找

  • str.index

    指数

  • str.rfind

    查找

  • str.rindex

    索引

  • re.search

    研究

  • match-objects

    匹配对象

翻译自: https://medium.com/better-programming/5-ways-to-find-the-index-of-a-substring-in-python-13d5293fc76d


http://www.taodudu.cc/news/show-994849.html

相关文章:

  • 趣味数据故事_坏数据的好故事
  • python分句_Python循环中的分句,继续和其他子句
  • python数据建模数据集_Python中的数据集
  • usgs地震记录如何下载_用大叶草绘制USGS地震数据
  • 数据可视化 信息可视化_更好的数据可视化的8个技巧
  • sql 左联接 全联接_通过了解自我联接将您SQL技能提升到一个新的水平
  • 科学价值 社交关系 大数据_服务的价值:数据科学和用户体验研究美好生活
  • vs azure web_在Azure中迁移和自动化Chrome Web爬网程序的指南。
  • selenium 解析网页_用Selenium进行网页搜刮
  • hive 导入hdfs数据_将数据加载或导入运行在基于HDFS的数据湖之上的Hive表中的另一种方法。
  • 大数据业务学习笔记_学习业务成为一名出色的数据科学家
  • python 开发api_使用FastAPI和Python快速开发高性能API
  • Power BI:M与DAX以及度量与计算列
  • 梯度下降法优化目标函数_如何通过3个简单的步骤区分梯度下降目标函数
  • seaborn 子图_Seaborn FacetGrid:进一步完善子图
  • 异常检测时间序列_时间序列的无监督异常检测
  • 存款惊人_如何使您的图快速美丽惊人
  • 网络传播动力学_通过简单的规则传播动力
  • 开源软件 安全风险_3开源安全风险及其解决方法
  • 自助分析_为什么自助服务分析真的不是一回事
  • 错误录入 算法_如何使用验证错误率确定算法输出之间的关系
  • pytorch回归_PyTorch:用岭回归检查泰坦尼克号下沉
  • iris数据集 测试集_IRIS数据集的探索性数据分析
  • flink 检查点_Flink检查点和恢复
  • python初学者_初学者使用Python的完整介绍
  • snowflake 数据库_Snowflake数据分析教程
  • 高级Python:定义类时要应用的9种最佳做法
  • 医疗大数据处理流程_我们需要数据来大规模改善医疗流程
  • python对象引用计数器_在Python中借助计数器对象对项目进行计数
  • 数字图像处理 python_5使用Python处理数字的高级操作

在Python中查找子字符串索引的5种方法相关推荐

  1. python中for循环遍历列表的几种方法

    列表在使用过程中,经常需要遍历列表的所有元素,对每个元素执行相同的操作.今天介绍python中for循环遍历列表的几种方法. 方法1:使用for循环简单结构遍历 首先我们新建一个城市列表,然后分别展示 ...

  2. Python在字符串中查找子字符串

    这是小白博主在刷leetcode时遇到的一道题,这是博主近日刷的leetcode题库时结果表现最好的一道题,故在此分享这份喜悦. 希望在以后的日子里可以继续进步,持之以恒. 目录 题目介绍 解题思路及 ...

  3. python查询缺失值所在位置使用scipy_在稀疏lil_matrix(Scipy / Python)中查找最大值及其索引...

    在Scipy稀疏lil_matrix对象中找到最大值及其对应的行和列索引的最佳方法是什么?我可以loop through the nonzero entries using itertools.izi ...

  4. python中list列表删除元素的4种方法

    在python列表中删除元素主要分为以下3种场景: 根据目标元素所在的索引位置进行删除,可以使用del关键字或pop()方法: 根据元素本身的值进行删除,可使用列表(list类型)提供的remove( ...

  5. Java中用三种方法输出字符串_java中两个字符串连接的三种方法

    java中两个字符串连接有以下三种方法: 第一种方法:使用+: 第二种方法:使用concat(): 第三种方法:使用append(): 如下代码: public class Practice { // ...

  6. python中实现上下文管理器的两种方法

    上下文管理器: python中实现了__enter__和__exit__方法的对象就可以称之为上下文管理器 实现方法一举例: def File(object): def __init__(self, ...

  7. python中计算n次方运算的四种方法【转】

    https://blog.csdn.net/u011699626/article/details/119582754 这里介绍一下python中n次方运算的四种书写形式,代码如下: # -*- cod ...

  8. 在字符串中查找子字符串

    今天中午一觉睡醒,刷b站,看见一个视频: 最浅显易懂的 KMP 算法讲解https://www.bilibili.com/video/BV1AY4y157yL?spm_id_from=333.1007 ...

  9. python lcm()_Python LCM –找到LCM的2种方法

    python lcm() In this article, we'll see different ways to find LCM in Python with program examples. ...

最新文章

  1. RDIFramework.NET V2.9版本多语言的实现
  2. 第四范式与丘成桐北京雁栖湖应用数学研究院签署战略合作协议
  3. Collections和Collection的区别:
  4. MySQL结果集 数据查询(重点)
  5. 大数据技术如何提升企业竞争力
  6. O_NONBLOCK与O_NDELAY有何不同?
  7. [CF617E]XOR and Favorite Number/[CQOI2018]异或序列
  8. php 仿安居客源码_python抓取安居客小区数据的程序代码
  9. 概要设计的必要性及写法
  10. 离散傅里叶变换公式推导
  11. 关于广告系统的定向,看这篇就够了
  12. Greater New York Region 2015 G compositions dp
  13. Elasticsearch:Standard Text Analyzer - 标准文本分析器
  14. 如何使用Node.js来制作电子音乐-和弦
  15. FFT 快速傅里叶变换 初探
  16. 创建IRP的相关内容
  17. 软件配置管理中三个基线概念
  18. fest556_FEST-Swing 1.2发布
  19. C语言,实现通讯录功能
  20. java 重定向端口_java – 重定向到另一个端口,保留所有其余的端口

热门文章

  1. 二叉树的广度优先遍历(层序遍历)
  2. 求序列第K大算法总结
  3. LRU缓存 数据结构设计(C++)
  4. Linux进程通信之文件
  5. Makefile(三)
  6. spring解析配置文件(三)
  7. DedeCMS 提示信息! ----------dede_addonarticle
  8. 使用.net Stopwatch class 来分析你的代码
  9. Sitemesh3的使用及配置
  10. JavaScript实现自适应宽度的瀑布流