Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and cut out a python substring

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!

like image 542
Riley Tench Avatar asked Sep 15 '26 05:09

Riley Tench


2 Answers

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")
like image 113
HennyH Avatar answered Sep 16 '26 20:09

HennyH


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')

like image 41
Dologan Avatar answered Sep 16 '26 19:09

Dologan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!