find position of a substring in a string(查找字符串中子字符串的位置)
问题描述
i am having a python string of format
mystr = "hi.this(is?my*string+"
here i need to get the position of 'is' that is surrounded by special characters or non-alphabetic characters (i.e. second 'is' in this example). however, using
mystr.find('is')
will return the position if 'is' that is associated with 'this' which is not desired. how can i find the position of a substring that is surrounded by non-alphabetic characters in a string? using python 2.7
Here the best option is to use a regular expression. Python has the re
module for working with regular expressions.
We use a simple search to find the position of the "is"
:
>>> match = re.search(r"[^a-zA-Z](is)[^a-zA-Z]", mystr)
This returns the first match as a match object. We then simply use MatchObject.start()
to get the starting position:
>>> match.start(1)
8
Edit: A good point made, we make "is"
a group and match that group to ensure we get the correct position.
As pointed out in the comments, this makes a few presumptions. One is that surrounded means that "is"
cannot be at the beginning or end of the string, if that is the case, a different regular expression is needed, as this only matches surrounded strings.
Another is that this counts numbers as the special characters - you stated non-alphabetic, which I take to mean numbers included. If you don't want numbers to count, then using r"(is)"
is the correct solution.
这篇关于查找字符串中子字符串的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找字符串中子字符串的位置
基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01