python - 查找并剪切出一个python子串

标签 python string find substring cut

这是我正在尝试做的事情:

我有一个长字符串:

s = asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf

我要剪掉子串:iwanttocutthisout

我将通过一个循环进行迭代,每次迭代时 s 的值都会改变。每次迭代唯一保持不变的是要删除的子字符串的开头和结尾:iwant 和 thisout。

给定这些参数,我如何截取子字符串?

感谢您的帮助!

最佳答案

您可以在 iwant 的出现索引(+len(iwant) 以取消包含 iwant)和 thisout 分别像这样:

>>> s = "asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf"
>>> s[s.index("iwant")+len("iwant"):s.index("thisout")]
'tocut'

图示:

"asdf23rlkasdfids(iwanttocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
                 ^          ^ 
                 |          |
            index("iwant")  |
                           index("thisout")

请注意这两个索引之间的切片(包括开头)将如何得到 iwanttocut。添加 len("iwant") 会导致:

"asdf23rlkasdfidsiwant(tocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
                      ^     ^ 
                 /----|     |
     index("iwant")         |
                           index("thisout")

关于python - 查找并剪切出一个python子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567731/

相关文章:

python - 如何在字符串中搜索多字串(完全匹配)?

string - ActionScript 3 .replace() 仅替换第一个实例

java - 字符串和数字的范围分组列表

macos - 查找特定秒数前创建的文件然后复制它

Python:对元组列表进行排序时的平局断路器(第一个元素的最大值,以及第二个元素的第一次出现)

python - Pycharm 升级到 4.0.5 导致问题

python - 获取最长重复字符串的索引

python - 在Linux上自动安装conda

添加项目后,C++ find() 函数不起作用

r - list.files 的性能问题