问题
Here is what I'm trying to do:
I have a long string:
s = asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf
I want to cut out the substring: iwanttocutthisout
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?
Thanks for your help!
回答1:
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'
Diagramatically:
"asdf23rlkasdfids(iwanttocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
^ ^
| |
index("iwant") |
index("thisout")
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")
回答2:
Use the sub()
function in the re
module like this:
clean_s = re.sub(r'iwant\w+thisout','',s)
Substitute \w+ for .+ if you're expecting non-word characters in your string and use * instead of + if there is a chance that there won't be any extra characters between the start and end tags (i.e. 'iwantthisout')
来源:https://stackoverflow.com/questions/17567731/find-and-cut-out-a-python-substring