Open In App

Insert a Variable into a String - Python

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to insert a variable into a string in Python. For example, if we have a variable containing the word "Hello" and another containing "World", we want to combine them into a single string like "Hello World". Let's explore the different methods to insert variables into strings effectively.

Using f-strings

f-strings (formatted string literals) were introduced in Python 3.6 and have quickly become the most recommended way to insert variables into strings. They are concise, readable and faster than other traditional methods.

Python
a = "Python"
res = f"This is {a} programming!"
print(res)

Output
This is Python programming!

Explanation: In an f-string, the variable a is inserted directly by placing it inside {} within a string prefixed with f, enabling dynamic content without manual concatenation.

Using format()

Before f-strings, the .format() method was the standard way to insert variables into strings. It remains widely used, especially in projects requiring compatibility with Python versions earlier than 3.6.

Python
a = "Hello"
b = "world"

res = "{} {}".format(a, b)
print(res)

Output
Hello world

Explanation: In the format() method, placeholders {} are used inside the string, and variables a and b are inserted by passing them to format(), allowing dynamic content without manual concatenation.

Using + operator

+ operator is a basic method to combine strings and variables, but it can get messy with multiple variables or different data types.

Python
a = "Hello"
b = "World"

res = a + " " + b
print(res)

Output
Hello World

Explanation: Using the + operator, the variables a and b are joined with a space between them, manually concatenating strings to create dynamic content.

Using % formatting

This method was used in earlier versions of Python and is still supported, but it's less preferred today due to better alternatives like format() and f-strings.

Python
a = "Python"
res = "This is %s programming!" % a
print(res)

Output
This is Python programming!

Explanation: In % formatting, the %s placeholder inside the string is replaced by the value of a, allowing variable insertion in a style similar to old C-style formatting.


Next Article

Similar Reads