Last modified: Feb 15, 2023 By Alexander Williams

Python: Add Variable to String & Print Using 4 Methods

In this tutorial, we're going to learn 4 methods to insert a variable into a string.

Method #1: using String concatenation

In the first method, we'll concentrate a variable with a string by using + character.

Let's see an example.


# variable
variable = "Python"

# insert a variable into string using String concatenation
print("Hello " + variable + " I'm Pytutorial")

Output:

Hello Python I'm Pytutorial

 

If your variable type is an integer, you must convert it to a string before concatenation.
To convert, we'll use the str() function.

 


# variable
variable = 33

# insert a variable into string using concatenation
print("Hello " + str(variable) + " I'm Pytutorial")

Output:

Hello 33 I'm Pytutorial

Method #2: using the "%" operator

With the "%" operator, we can insert a variable into a string.
%s: for string.
%d: for integer.

Let's see how to use the method?


# variable
variable = "Python"

# insert a variable into string using "%" operator
insert_var = "Hello %s I'm Pytutorial"%variable

#print
print(insert_var)

Output:

Hello Python I'm Pytutorial

 

inserting multi variables:

 


# variable
variable_1 = "Python"
variable_2 = "Django"

# insert multi variables into string using "%" operator
insert_var = "Hello %s and %s I'm Pytutorial"%(variable_1, variable_2)

#print
print(insert_var)

Output:

Hello Python and Django I'm Pytutorial

 

insert an integer variable into a string using %d:

 


# variable
age = 20

# insert multi variables int into a string
insert_var = "Hello Python and Django I'm Pytutorial I'm %d years old"%age

#print
print(insert_var)

Output:

Hello Python and Django I'm Pytutorial I'm 20 years old

Method #3: using the format() function

Another method to insert a variable into a string is using the format() function.


variable_1 = "Python"
variable_2 = "Django"
age = 20

# insert variables into string using format()
insert_var = "Hello {} and {} I'm Pytutorial I'm {} years old".format(variable_1, variable_2, age)

#print
print(insert_var)

Output:

Hello Python and Django I'm Pytutorial I'm 20 years old

Method #4: using f-string

f-string is my favorite method to insert a variable into a string because it's more readable.
Let's see how to use it.

Note: this method works on Python >= 3.6.


variable_1 = "Python"
variable_2 = "Django"
age = 20

# insert variables into string using f-string
insert_var = f"Hello {variable_1} and {variable_2} I'm Pytutorial I'm {age} years old"

#print
print(insert_var)

Output:

Hello Python and Django I'm Pytutorial I'm 20 years old

Conclusion

In this tutorial, we've learned four methods to insert a variable into a string. All methods work perfectly.
Happy codding.