Python查找第n个子串的技巧分享

yipeiwu_com6年前Python基础

Problem

Python中str类自带的find、index方法可以返回第一个匹配的子串的位置,但是如果实际使用中需要查找第2个甚至第n个子串的位置该怎么办呢。也许有的码友可能会用到第二第三个参数,指定查找的起始、终止位置。但是在很多情况下,接收到的一个字符串可能是未知的,强制限定起始位置可能导致代码在某些情况下不能适用。

Solution

采用嵌套的方法调用find或者index。

 str_exp = "aaabbbbccc"
 pos_n = str_exp.index("a", str_exp.index("a")+1)
 print(pos_n)

原理很简单,第一次查找返回的位置加1作为第二次查找的起始参数。加1是因为start参数位置是被包含的,采用的闭区间的语义。也不用担心会越界,python底层已经做了处理。

也可以写一个单独的函数来进行查找操作。

def find_n_sub_str(src, sub, pos, start):
 index = src.find(sub, start)
 if index != -1 and pos > 0:
  return find_n_sub_str(src, sub, pos - 1, index + 1)
 return index

pos表示第n个子串,从0开始。start为起始位置。此处使用find而不用index是因为index在查找失败时会报出异常,而find不报异常返回-1。从健壮性考虑使用find。

看来递归使用起来还是可以解决很多编程实践过程中遇到的工程问题。:)

Attention

1、左闭右开特性

str.index(self, sub, start=None, end=None)
str_tmp[start:end]

默认的是左闭右开,即包含start的位置,却不包含end的位置。在使用过程中需要注意一下。同样左闭右开的还有切片操作str_tmp[start:end]。

示例如下:

 str_exp = "aaabbbbccc"
 print(str_exp)
 print(str_exp[str_exp.index("a"):str_exp.rindex("c")])
aaabbbbccc
aaabbbbcc

2、find与index差别

find是不会报出异常的,即查找子串失败的情况下返回-1,而index在查找子串失败时会报异常。

示例如下:

 str_tmp = "aaaabbbbccccdddd"
 print(find_n_sub_str(str_tmp, "a", 5, 0))
 print(str_tmp.find("a", 7))
 print(str_tmp.index("a", 7))
-1
-1
Traceback (most recent call last):
 File "/usr/local/pycharm-community-5.0.4/helpers/pydev/pydevd.py", line 2411, in <module>
 globals = debugger.run(setup['file'], None, None, is_module)
 File "/usr/local/pycharm-community-5.0.4/helpers/pydev/pydevd.py", line 1802, in run
 launch(file, globals, locals) # execute the script
 File "/usr/local/pycharm-community-5.0.4/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
 exec(compile(contents+"\n", file, 'exec'), glob, loc) 
 File "/usr/local/workspace/pycharmPro/StockAI/StockAI/DbDealer.py", line 140, in <module>
 print(str_tmp.index("a", 7))
ValueError: substring not found

以上这篇Python查找第n个子串的技巧分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python超时重新请求解决方案

在应用中,有时候会 依赖第三方模块执行方法,比如调用某模块的上传下载,数据库查询等操作的时候,如果出现网络问题或其他问题,可能有超时重新请求的情况; 目前的解决方案有 1. 信号量,但不...

在cmder下安装ipython以及环境的搭建

在cmder下安装ipython以及环境的搭建

打开cmder 1.移动到D盘 输入命令:D: 2.创建文件夹 λ mkdir myApp 3.创建python自带的虚拟环境 λ python -m venv...

Python函数的周期性执行实现方法

本文实例讲述了Python函数的周期性执行实现方法。分享给大家供大家参考,具体如下: 需要用到python的sched模块: #coding=utf-8 import time,sc...

nginx+uwsgi+django环境搭建的方法步骤

环境搭建 1.安装uwsgi、nginx和django apt install nginx pip install uwsgi pip install django 2.测试...

jupyter安装小结

前段时间一直使用pycharm写pandas程序,对于大数据开发而言,开发一般是走一步想一步,pycharm不适合。网上推荐使用jupyter notebook,它是一个web版的编辑器...