'How do I put a variable’s value inside a string?

I would like to put an int into a string. This is what I am doing at the moment:

num = 40
plot.savefig('hanning40.pdf') #problem line

I have to run the program for several different numbers, so I'd like to do a loop. But inserting the variable like this doesn't work:

plot.savefig('hanning', num, '.pdf')

How do I insert a variable into a Python string?



Solution 1:[1]

plot.savefig('hanning(%d).pdf' % num)

The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Solution 2:[2]

Oh, the many, many ways...

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

Using str.format():

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the preferred way since 3.6

Using f-strings:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

This is the new preferred way:


Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

Solution 3:[3]

With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

With the example given in the question, it would look like this

plot.savefig(f'hanning{num}.pdf')

Solution 4:[4]

Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().

"hello " + str(10) + " world" = "hello 10 world"

Hope that helps!

Solution 5:[5]

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

Solution 6:[6]

If you would want to put multiple values into the string you could make use of format

nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))

Would result in the string hanning123.pdf. This can be done with any array.

Solution 7:[7]

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

Solution 8:[8]

You can make dict and substitute variables in your string.

var = {
        "name": "Abdul Jalil",
        "age": "22"
    }
temp_string = """
My name is %(name)s. 
I am %(age)s years old.
""" % var

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alexeypetrenko
Solution 2 FLAK-ZOSO
Solution 3 joelostblom
Solution 4 goggin13
Solution 5 Spikatrix
Solution 6 Jonathan R
Solution 7 Raja
Solution 8 abduljalil