336

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?

martineau
  • 112,593
  • 23
  • 157
  • 280
Gish
  • 3,439
  • 3
  • 16
  • 6

9 Answers9

678

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()))
FLAK-ZOSO
  • 3,115
  • 3
  • 5
  • 23
Dan McDougall
  • 8,217
  • 3
  • 16
  • 17
  • 19
    To use the format string operator with multiple arguments, one can use a tuple as operand: `'foo %d, bar %d' % (foo, bar)`. – fiedl Aug 08 '14 at 15:38
  • 13
    Your neat trick kind of works with the new format syntax too: `plot.savefig('hanning{num}s.pdf'.format(**locals()))` – pix Oct 10 '14 at 04:30
  • 14
    With the introduction of f-strings in Python 3.6, this can now be written as `plot.savefig(f'hanning{num}.pdf')`. I added an answer with this info. – joelostblom May 26 '17 at 15:30
  • had issues using locals () inside a function calling a global variable; used % globals() instead which worked – lobi Feb 14 '20 at 12:40
  • "There should be one -- _and preferably only one_ -- obvious way to do it.". – MAChitgarha Aug 15 '21 at 21:38
  • @MAChitgarha: Wishful thinking, but not something that could possibly hold for a language that's evolved over time. – martineau Feb 07 '22 at 23:58
184
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

alexeypetrenko
  • 168
  • 2
  • 7
Amber
  • 477,764
  • 81
  • 611
  • 541
  • 50
    Note that the `%` operator is deprecated as of Python 3.1. The new preferred way is to make use of the `.format()` method as discussed in [PEP 3101](https://www.python.org/dev/peps/pep-3101/) and mentioned in Dan McDougall's answer. – Chris Mueller Jul 16 '15 at 14:18
  • The `%` operator is not deprecated - it is just not the preferred way now. – kaya3 Sep 13 '21 at 12:59
183

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')
joelostblom
  • 35,621
  • 16
  • 134
  • 143
  • 3
    It appears that [f-strings are compatible with multiline strings](https://stackoverflow.com/a/47023489/3357935). – Stevoisiak Oct 30 '17 at 20:23
19

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!

goggin13
  • 7,432
  • 7
  • 28
  • 44
  • 7
    While this answer is correct building strings with `+` should be avoided as its extremely expensive – slayton Dec 26 '13 at 17:31
6

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
Spikatrix
  • 19,653
  • 7
  • 38
  • 77
Yehonatan
  • 1,132
  • 2
  • 11
  • 20
5

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.

Jonathan R
  • 3,060
  • 2
  • 19
  • 33
3

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)]
Raja
  • 933
  • 11
  • 11
0

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
abduljalil
  • 89
  • 1
  • 2
-8

You just have to cast the num varriable into a string using

str(num)
Ole
  • 1
  • 3