How To Insert Variables Into a String in Python

insert variables into a string python

Learn how to insert different types of variables such as int, float, boolean, and string into a string in Python using different techniques.

What Is a Variable?

A Python variable is like a container used to store different types of values. Just as we store items in real life containers such as food, groceries, clothes, and other things, in Python, we can store values of different data types, such as integers (numbers), floats (numbers with decimals), strings (text), and booleans (true or false values) in a variable.

Why Insert Variables Into String in Python?

Imagine, it’s your birthday, and you are making invitation cards for your friends and family. Instead of rewriting the same content for everyone with their names, you create an entire card with a blank space to write the guest’s name. This will reduce a lot of time and effort, as you will be reusing the same cards for everyone instead of rewriting again and again for each person. Additionally, it will help avoid mistakes since you will be writing the content only once instead of rewriting it repeatedly for each person

Inserting variables to a string analogy

Similarly, in Python, you can use variables to insert information into strings whenever needed. Just as you can customize the invitation card for each person, you can customize each string for different outputs in Python by inserting different types of variables into it.

How To Insert Variables Into a String in Python?

To insert variables into a string, there are several ways to do so in Python. We will be discussing all the possible methods to insert a variable into a string using code, real life examples, and visual analogies.

Insert Variables Into a String Using the Comma

In Python, the simplest and easiest way to insert a variable into a string is by using a comma ‘,’. Imagine you are working at an online shopping center, and you receive hundreds of orders daily. Instead of rewriting the same order confirmation letter for each customer, you can write the letter once and insert the order number (integer), order price (float), and customer name (string) by simply placing a comma between them.

To use a comma, write the name of the variable after a string, placing a comma in between. The value of that variable will then be inserted into the string

Code

customer_name = "John"
order_number = 12345
order_price = 99.99

print("Hello,", customer_name , "!", "Your order number", order_number, "worth $", order_price, "has been confirmed.")

Output

Hello, John ! Your order number 12345 worth $ 99.99 has been confirmed.

Use the Concatenation Operator ‘+

You can directly concatenate strings in Python using ‘+‘ operator but it’s only possible for string data type and not for other data types such as int, float and Boolean. Imagine that you have a container designed to store only wrapped candies. If you have some unwrapped candies, you first need to wrap them before placing them in the container.

Inserting variables to a string analogy

Similarly, in Python, if you want to insert variables of different data types, such as integers or floats, into a string, you must first convert those variables into strings, just like wrapping the candies before putting them in the container. For this purpose, you can use the str() method to convert a variable of different data type into string.

To use the str() method, you pass a variable as a parameter to the str() function, and it converts that variable into a string. Then it can easily be concatenated with a string using a ‘+’ operator.

Code

name = "Dilawar"
age = 20
height = 5.6
result = "My name is " + name + ", I am " + str(age) + " years old, and my height is " + str(height) + " feet."
print(result)

Output

My name is Dilawar, I am 20 years old, and my height is 5.6 feet.

Use f-string to Insert Multiple Variables Into a String

The f-string (also known as formatted string literals ) allows you to insert a variable into a string simply by using placeholders, denoted by curly braces i.e ‘{}’. It is an easy and efficient way to insert different types of variables into a string. It is to be noted that F-strings only work in Python 3.6 or greater. If you are using an older version, then this method might not work for you

To use f-strings, you have to mention lowercase or uppercase ‘f’ before the quotation marks of your string. Then, you can directly insert a variable in string by writing the name of variable within the curly braces.

Code

name = "Dilawar"
age = 20
height = 5.6
result = f"My name is {name}, I am {age} years old, and my height is {height} feet."
print(result)

Output

My name is Dilawar, I am 20 years old, and my height is 5.6 feet.

Use the format() Method

The format() method inserts different types of variables into a string without worrying about converting them into strings or using the + operator. It works similar to F-strings but in F-strings, you have to enter the variable name inside the placeholders(curly braces), while in the format method, we leave the curly braces empty and then specify the variables by passing them as parameters to the format() function in the order they appear in the string. It’s important to insert them in the correct order, otherwise, the values may be misplaced.

In the format() method, the placeholders are replaced by the values passed to the format() function. The placeholders are of two types, i.e positional placeholders and named placeholders. The placeholders are replaced with the values of those variables, based on their positions.

Code

name = "Dilawar"
age = 20
height = 5.6
result = "My name is {}, I am {} years old, and my height is {} feet.".format(name, age, height)
print(result)

Output

My name is Dilawar, I am 20 years old, and my height is 5.6 feet.

Named Placeholders

The name placeholders work similar to the positional placeholders but in named placeholders, you define the variables in the format() function. In other words,you pass values to the format() function with their names. Another difference is that in named placeholders, you have to write the variable names inside the curly braces, just like you do with formatted strings

Code

result = "My name is {name}, I am {age} years old, and my height is {height} feet.".format(name="Dilawar", age=20, height=5.6)
print(result)

Output

My name is Dilawar, I am 20 years old, and my height is 5.6 feet.

Use % Operator

In Python, the % operator (also known as the modulus operator) can be used to insert variables into a string. The % operator works as a placeholder, where specific characters represent the type of data you want to insert into the string. You need to type a specific character after the % operator for each data type, such as %s for a string, %d for an integer, and %f for a floating-point number.

After placing all the placeholders with their specific characters correctly, you can list all the variable names enclosed in parentheses '()‘ in the order they appear in the string, and place  ‘%’ operator before it. When the code is run, these placeholders will be replaced with the values of the variables mentioned at the end. Keep in mind that you must use the correct characters for each data type, or it will result in an error.

Code

name = "Dilawar"
age = 20 
height = 5.6       
result = "My name is %s, I am %d years old, and my height is %.1f feet." % (name, age, height)
print(result)

Output

My name is Dilawar, I am 20 years old, and my height is 5.6 feet

Placeholders for Data Types Using the % Operator

Data TypePlaceholderDescription
String%sRepresents a string value
Integer%dRepresents an integer value
Floating-point number%fRepresents a floating-point number
Hexadecimal integer%xRepresents an integer in hexadecimal format
Octal integer%oRepresents an integer in octal format
Scientific notation (lowercase)%eRepresents a number in scientific notation (lowercase ‘e’)
Scientific notation (uppercase)%ERepresents a number in scientific notation (uppercase ‘E’)
Literal ‘%’ character%%Inserts a literal ‘%’ character

Conclusion

Inserting variables into strings is necessary in many cases, and it makes our code more precise. In Python, there are several ways to do this, including using commas, the concatenation method, f-strings, the format() method, and the % operator. Each method is useful in its own way, depending on the scenario in which you are using it.

FAQs

Why would you insert variables into a string in Python?

Inserting variables into strings makes your code reusable, and efficient. It helps to easily customize the content of strings without rewriting the entire text multiple times, just like personalizing a message for each recipient.

What is the simplest way to insert variables into a string in Python?

The simplest way is by using commas in a print() statement. This method allows you to insert different data types directly into a string without any conversion.

What are f-strings, and how do they work in Python?

F-strings (formatted string literals) are a way to embed variables directly into a string using curly braces {} as placeholders. You prefix the string with f or F, and it’s an efficient and readable way to format strings in Python 3.6 and above.

What is the difference between using the format() method and f-strings for inserting variables into a string?

Both methods use curly braces {} as placeholders, but in f-strings, you directly place the variable names inside the braces, while in the format() method, you leave the braces empty and pass the variables as parameters to the format() function.

How do you use the % operator for string formatting in Python?

The % operator is used to insert variables into strings by placing placeholders (like %s, %d, %f) within the string. After the string, you list the variables in parentheses, and they are inserted based on the placeholders.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top