Contents
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. An example is given below.
Python Program
var1 = 'ABC'
mystring = f'hello {var1}'
print(mystring)
Run In the above program, we have a variable named var1 and we inserted this variable in the string using formatted strings.
Example 1: 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 Output
The point in XY plane is (25,88)
Example 2: String Variables in Strings
In this example, we will take string literals in variables and try to insert these variables inside the string using formatted string.
Python Program
name = 'ABC'
place = 'Houston'
mystring = f'My name is {name}. I live in {place}.'
print(mystring)
Run 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.