How to place Variables in String in Python?

Python – Variables in String

To place variables in string, we may use formatted string literals.

Place the character f before you start a string literal with single/double quotes as shown below.

f'hello world'

Now, we can reference variables inside this string. All we need to do is enclose the variables with curly braces {variable} and place this variable inside the string value, wherever required. A quick example is given below.

Python Program

var1 = 'ABC'
mystring = f'hello {var1}'
print(mystring)
Run Code Copy

In the above program, we have a variable named var1 and we inserted this variable in the string using formatted strings.

Examples

1. Write variables in strings

In this example, we will take integers in variables and try to insert these variables inside the string using formatted string.

Python Program

x = 25
y = 88
mystring = f'The point in XY plane is ({x},{y})'
print(mystring)
Run Code Copy

Output

The point in XY plane is (25,88)

2. Format string values in a given string

In this example, we will take string values in variables, name and place, and try to insert these variables inside the string using string formatting.

Python Program

name = 'ABC'
place = 'Houston'
mystring = f'My name is {name}. I live in {place}.'
print(mystring)
Run Code Copy

Output

My name is ABC. I live in Houston.

Summary

In this tutorial of Python Examples, we learned how to place variables in string literal, with the help of example programs.

Quiz on

Q1. What is the output of the following program?

x = 12
print(f'The value of x is {x}.')
Run Code Copy
Not answered
Code copied to clipboard successfully 👍