Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a variable 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?

like image 386
Gish Avatar asked Jun 02 '10 19:06

Gish


People also ask

Can you put a variable in a string?

With the "%" operator, we can insert a variable into a string.

How do you write a variable inside a string?

Instead of using quotes (double quotes or single quotes), we use template literals defined with the backticks (` character in keyboard). We place the string in the backticks and embed our variables in the sentence. Following are the usages of template literals.

How do you put a variable inside a string in JavaScript?

You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation. The difference is, the interpolation example is much easier to read.


2 Answers

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:

  • PEP-502
  • RealPython
  • PEP-536

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals())) 
like image 121
Dan McDougall Avatar answered Sep 30 '22 04:09

Dan McDougall


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

like image 28
Amber Avatar answered Sep 30 '22 05:09

Amber