I'm trying to create some variables within string with words that follows a specific format.
For instance, my original string is:
string = '@Cost1 + (@Cost2 + @Cost3) / @Revenue1 * 1.2'
I have already created a dictionnary as follow:
mydict = {'Cost1' : 10, 'Cost2' : 5, 'Cost3' : 1, 'Revenue1' : 10}
What I would like to create is a function that will replace the @Cost1 (for instance) by:
mydict.get('Cost1')
so that I can consider the @ in my string as a marker for variable and look for the value in my dictionnary.
Therefore, my intent is to:
- replace the @ by
mydict.get('
--> that is very easy with the string.replace() function - add
')
at the end of the chain of alphabet letters that follows the @words --> this one I'm having difficulty to implement
I was considering a for loop but struggling with the logic to add the "')" after the end of each word preceded by an @. Also thought about generator but not too sure
Also, I would like to add a check that every @Cost1, @Cost2 etc. is in my dictionnary, but this one I should be able to do it.
Any help is welcome about this
Thank you !
Eric
Edit:
following your comment, I would like my final output to be:
string = mydict.get('Cost1') + ( mydict.get('Cost2') + mydict.get('Cost3') ) / mydict.get('Revenue1') * 1.2'