-3

In Ruby I can do this:

"This is a string with the value of #{variable} shown."

How do I do that same thing in Python?

Terry G Lorber
  • 2,932
  • 2
  • 23
  • 33

3 Answers3

3

The modern/preferred way is to use str.format:

"This is a string with the value of {} shown.".format(variable)

Below is a demonstration:

>>> 'abc{}'.format(123)
'abc123'
>>>

Note that in Python versions before 2.7, you need to explicitly number the format fields:

"This is a string with the value of {0} shown.".format(variable)
3

You have a lot of options.

"This is a string with the value of " + str(variable) + " shown."

"This is a string with the value of %s shown." % (str(variable))

"This is a string with the value of {0} shown.".format(variable)
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
1

this is one of the way we can also do

from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46