Basically I'm trying to take a Template String and store it in a variable for later use. I'm new with Python and programming languages in general so I'm finding difficulty in doing this. This is the code I'm using to generate the string:

from string import Template
s = Template('$who has $amount dollars.')
s.substitute(who='Merideth', amount='65')

Fairly simple, but how do I take that all and store it in a variable? I'd like to store the string in a variable and print it later.

Thanks in advance. Hate to bother with a beginner question, but we all have to start somewhere...

Basically I'm trying to take a Template String and store it in a variable for later use. I'm new with Python and programming languages in general so I'm finding difficulty in doing this. This is the code I'm using to generate the string:

from string import Template
s = Template('$who has $amount dollars.')
s.substitute(who='Merideth', amount='65')

Fairly simple, but how do I take that all and store it in a variable? I'd like to store the string in a variable and print it later.

Thanks in advance. Hate to bother with a beginner question, but we all have to start somewhere...

's.template' contains the original string passed to Template().
s.substitute() returns a string object which can be assigned to a variable.
HTH

's.template' contains the original string passed to Template().
s.substitute() returns a string object which can be assigned to a variable.

Yes, and it doesn't actually change s itself either. One confusing-but-it-makes-sense-when-you-get-used-to-it feature about Python is that strings are immutable, which means that all string methods like substitute() return their results instead of changing the original.

Jeff

The Python language itself depends heavily on highspeed mappings called dictionaries. Strings are used as keys and have to be immutable objects. Jeff is right, it takes a while to sink in.

You actually should store your result in a variable ...

from string import Template
 
s = Template('$who has $amount dollars.')
str1 = s.substitute(who='Merideth', amount=65)
#same as --> str1 = s.substitute({'who': 'Merideth', 'amount': 65})
 
print str1  # Merideth has 65 dollars.

The Python language itself depends heavily on highspeed mappings called dictionaries. Strings are used as keys and have to be immutable objects. Jeff is right, it takes a while to sink in.

You actually should store your result in a variable ...

from string import Template
 
s = Template('$who has $amount dollars.')
str1 = s.substitute(who='Merideth', amount=65)
#same as --> str1 = s.substitute({'who': 'Merideth', 'amount': 65})
 
print str1  # Merideth has 65 dollars.

Yes, that was exactly what I was looking for! Funny how I try everything but that. Thanks a bunch.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.