python include variable in string

How to Put Variable in String in Python

Generally, developers use literal strings to specify filenames and paths, and other things in python. But sometimes you may need to put variable in string in Python. In this article, we will learn how to put variable in string in Python.


How to Put Variable in String in Python

Let us say you have the following variable in python.

num = 40

Let us say you want to run the following command.

plot.savefig('test40.pdf')

But you want to pass the number 40 in above command, using variable num.

Here are the different ways to do this.

1. Using String Concatenation

We use str() function to convert number into string, and then use concatenate (+) operator to put variable in string.

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

Please note, you need to convert number into string before concatenating with other strings otherwise you may get an error due to data type mismatch.

2. Using format() function

You can also use format() function as shown below to concatenate literal strings with variables.

plot.savefig('test{0}.pdf'.format(num))

3. Using Conversion Specifiers

You can also use conversion specifiers to substitute string variables in python strings.

plot.savefig('test%s.pdf' % num)
OR
plot.savefig('test%(num)s.pdf' % locals())

4. Using String Template

You can also use string template to include variables in string.

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

In this article, we have learnt several simple ways to easily include a variable in another string. You can customize it as per your requirement. The concatenation method is one of the most common ways to include variable in string in Python.

Also read:

How to Fix ValueError:setting an array element with sequence
How to Fix ‘ASCII codec can’t encode’ error in Python
How to Curly Braces in String in Python
How to Set Timeout on Function Call in Python
How to Set Default Value for Datetime Column in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *