3

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!

jparthj
  • 1,606
  • 3
  • 20
  • 44
Riley Tench
  • 33
  • 1
  • 1
  • 3

3 Answers3

3

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")
HennyH
  • 7,794
  • 2
  • 29
  • 39
3

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

Dologan
  • 4,554
  • 2
  • 31
  • 33
1
s = s.replace('iwantthisout', '')
Rogelio Triviño
  • 5,961
  • 3
  • 22
  • 17