In Python programming, string interpolation is a common process used to insert variables inside string literals utilizing placeholders. One way to accomplish this task is by using double quotes to include variables within a string. In this tutorial, we will demonstrate how to use variables effectively in double quotes in Python.
Step 1: Defining variables and strings
First, let’s define some variables and a string that includes those variables. For this tutorial, we will work with an example of someone’s first name, last name, and age.
1 2 3 |
first_name = "John" last_name = "Doe" age = 30 |
Now, let’s create a string that will include these variables. It should look like this:
1 |
info = f"{first_name} {last_name} is {age} years old." |
In this example, we used an f-string to include the variable names within the curly braces {}
. With double quotes enclosing the entire string, Python can now recognize the variables being used.
Step 2: Display the formatted string
Now that we have our string with variables inside, let’s print the resulting output:
1 |
print(info) |
The output should look like this:
John Doe is 30 years old.
The f-string automatically substituted the variables’ values into the string, providing a neatly formatted output.
Alternative method: Using .format()
method
In addition to f-strings, you can also use the .format()
method to insert variables into strings. Here is the same example using this method:
1 2 |
info = "{} {} is {} years old.".format(first_name, last_name, age) print(info) |
The output will be the same:
John Doe is 30 years old.
In this case, the curly braces {}
serve as placeholders and are filled with the variables in the same order as they appear in the .format()
method.
Full code
Here’s the full code using the f-string method:
1 2 3 4 5 |
first_name = "John" last_name = "Doe" age = 30 info = f"{first_name} {last_name} is {age} years old." print(info) |
And here’s the full code using the .format()
method:
1 2 3 4 5 |
first_name = "John" last_name = "Doe" age = 30 info = "{} {} is {} years old.".format(first_name, last_name, age) print(info) |
Conclusion
In this tutorial, you have learned how to use variables effectively in double quotes with Python. You can choose between the f-string method or the .format()
method to insert variables into your strings. Both approaches provide a convenient way to include variables directly in string literals and generate neat and readable outputs.