In: Computer Science
Give an example of variable substitution work would be to make a program that can just take a string and replace $foo$ with a given string, s. Then you could convert that to a function.
from string import Template #import the Template class from Python’s built-in string module #Template strings are not a core language feature but they’re supplied by the string module in the standard library. #By default you can use any substitution like string interpolation,String formatting,String formatting(%operator) #here i have shown you the Template strings (Standard Library) # In my opinion, the best time to use template strings is when you’re handling formatted strings generated by users of your program. # Due to their reduced complexity, template strings are a safer choice. def VariableSubstitute(s): t = Template('Hey, $foo!') #storing default content and replacing it with s for $foo value return t.substitute(foo=s) #here s=student since we are passing string s to function definition of VariableSubstitute print(VariableSubstitute("Student")); #finally printing the value of string after replacing it with s
Output: // Hope it was helpful. If you have any doubts feel free to add comments. Thanks in advance.