Find and cut out a python substring

吃可爱长大的小学妹 提交于 2020-01-25 06:30:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!