Question

Suppose i have two strings in python:

    str1 = 'WeDrank$varCupCoffeeToday'
    str2 = 'WeDrank2CupCoffeeToday'

We can clearly see that there the difference between them are $var and 2. How do we obtain 2 as an output assuming $var may be in any position i.e

    str1 = 'WeDrank2CupCoffee$var'
    str2 = 'WeDrank2CupCoffeeToday'

So here the output should be Today. Anticipating the best suggestion. Thanks in advance.

Was it helpful?

Solution

Split on the token '$var', then replace the two parts from the left and right sides respectively with an empty string, and you will get the value of the token.

>>> str1 = 'WeDrank$varCupCoffeeToday'
>>> str2 = 'WeDrank2CupCoffeeToday'
>>> parts = str1.split('$var')
>>> str2.replace(parts[0],'').replace(parts[1],'')
'2'
>>> str1 = 'WeDrank2CupCoffee$var'
>>> str2 = 'WeDrank2CupCoffeeToday'
>>> parts = str1.split('$var')
>>> str2.replace(parts[0],'').replace(parts[1],'')
'Today'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top