-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?

0

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

@C.B.: 2.7 and up, actually.
@MartjinPieters really? I tried that on 2.7 and it threw errors at me. Maybe it was 2.6
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')

2 Comments

Also good, though possibly overkill for his particular example.
@TheSoundDefense i thought same answer as you but your quick.do it first or do it different :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.