查找并切出python子字符串 [英] Find and cut out a python substring
问题描述
这就是我想要做的:
我的字符串很长:
s = asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf
我想剪切出子字符串:iwanttocutthisout
I want to cut out the substring: iwanttocutthisout
我将遍历一个循环,并且每次迭代时s的值都会改变.每次迭代唯一不变的是要删除的子字符串的开头和结尾:iwant和thisout.
I will be iterating through a loop and with each iteration the value of s will change. The only thing that will stay the same with each iteration is the begining and end of the substring to be cut out: iwant and thisout.
在给定这些参数的情况下,如何剪裁子字符串?
How can I cut out the substring, given these parameters?
感谢您的帮助!
推荐答案
您可以分别在iwant
(+len(iwant)
排除iwant
)和thisout
的出现索引之间进行切片所以:
You can do a slice between the index of occurance of iwant
(+len(iwant)
to dis-include iwant
) and thisout
respectively, like so:
>>> s = "asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf"
>>> s[s.index("iwant")+len("iwant"):s.index("thisout")]
'tocut'
钻石般地:
"asdf23rlkasdfids(iwanttocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
^ ^
| |
index("iwant") |
index("thisout")
请注意,这两个索引之间的切片(从开始算起)如何得到iwanttocut
.添加len("iwant")
将导致:
Notice how slicing between these two indexes (beginning inclusive) would get iwanttocut
. Adding len("iwant")
would result in:
"asdf23rlkasdfidsiwant(tocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
^ ^
/----| |
index("iwant") |
index("thisout")
这篇关于查找并切出python子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!