0

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Bishwash
  • 854
  • 1
  • 9
  • 22

1 Answers1

4

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'
2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • unfortunately it won't for urls – Bishwash Feb 28 '14 at 22:51
  • Finally i found the good solution that will work for simple strings and url is replace lstrip with replace function as:str2.replace(parts[0],'').replace(parts[1],'') – Bishwash Feb 28 '14 at 22:53
  • what if we have str1 = 'WeDrank$var1CupCoffeeTodayWith$var2Persons' and str2 ='WeDrank2CupCoffeeTodayWith6Persons' situation? I mean for a dynamic situation where there might be any number of $var ? – Bishwash Mar 01 '14 at 17:58
  • @user2789099 You failed to mention that in your original question... also, I don't see how this wouldn't work for a URL. – 2rs2ts Mar 01 '14 at 18:05
  • Yes, I had not mentioned, even though i am asking. Yes, I tried with url it didn't worked. – Bishwash Mar 01 '14 at 18:13
  • @user2789099 can you post the input you used which didn't work? Maybe I can explain that. – 2rs2ts Mar 01 '14 at 18:19
  • str1 = 'http://127.0.0.1:8000/setLanguage/$var/' and str2 = 'http://127.0.0.1:8000/setLanguage/en/' are the two inputs for which it seem to be working but not working.. – Bishwash Mar 01 '14 at 18:38
  • @user2789099 Wow, thanks for pointing that out! Turns out I was wrong about [what `lstrip` and `rstrip` do](http://stackoverflow.com/a/4840805/691859). – 2rs2ts Mar 01 '14 at 19:32
  • you are welcome.. Did you find the reason that why it didn't worked? – Bishwash Mar 01 '14 at 19:50
  • @user2789099 Read the link I provided in my comment. As far as using multiple variables goes, you could use the `re` module to help with that, but I suggest you open a new question for that. – 2rs2ts Mar 02 '14 at 01:05