aacealo aacealo - 2 years ago 121
Python Question

How to subtract known substring from larger string

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.

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download