How to subtract known substring from larger string

15,483

You can replace parts of a string with some other string.

"Substracting" would be replacing a substring with an empty string:

>>> 'Hello world I am Bob'.replace('Hello world', '')
' I am Bob'
Share:
15,483
aacealo
Author by

aacealo

Updated on June 11, 2022

Comments

  • aacealo
    aacealo almost 2 years

    I have been trying to deconstruct a string in the following way:

    Full String

    str = 'Hello world I am Bob'
    

    Substring 1

    sub_str1 = 'Hello world'
    

    Substring 2

    sub_str2 = 'world I'
    

    Desired Outcome:

    1. Using substring 1:

      Apply some regular expression to get:

      answer = ' I am Bob'
      
    2. Using substring 2:

      answer = 'Hello  I am Bob'
      

    I have tried a number of different approaches with regular expression, but I have just started using them and am not at all proficient.

  • aacealo
    aacealo over 7 years
    Thanks. I'm just curious to know if you think this is faster than a regex? I'd use timeit to test, but I can't figure out a regular expression that will accomplish the same thing.
  • Geoff
    Geoff over 7 years
    s/Hello world// is the replacement regex
  • zvone
    zvone over 7 years
    @aacealo Regex to find "Hello world" is "Hello world". This sam thing with regex would be re.sub('Hello world', '', 'Hello world I am Bob'). I did not time it, but I am sure regex is much slower. The only reason to use regex is if you want to do something more complex, e.g. replace the first two words whatever they are: re.sub(r'^ *\w+ +\w+ +', '', 'Hello world I am Bob')
  • aacealo
    aacealo over 7 years
    Okay, I think I'll just go with your approach. It makes sense, and it's simpler than trying to learn regular expression.