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 +.

Let's see the following 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 string before concertante.
To converting 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

By using the "%" operator, we can insert a variable wherever we want into a string.
%s: for string
%d: for integer

Let's see how to use this 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 integer variable into 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 by 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

In the last method in this tutorial, we'll see how to use the f-string.

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

Today, we learned about inserting a variable in a string by using many methods, and the question arises is:
What is the best method for that?
Method #4 is the best for me.

English today is not an art to be mastered it's just a tool to use to get a result