When working with Python, it’s essential to know how to print variable values within strings. There are multiple ways for you to do this in your programs.
This article is designed to guide beginner developers through the process of printing variables in a string, covering the basic use of the print() function, concatenation, and the more modern and efficient approach of using f-strings.
Let’s dive in and explore the different methods to achieve this in Python.
Basic Use of the print() Function to Print Variables in Python
One of the most fundamental tasks in programming is displaying variable values. You can use Python’s print() function for this purpose. It allows you to output text and variable values to the console.
Here’s how you can use the print() function to display different variable types:
Printing a string
message = "Hello, World!"
message contains the string "Hello, World!". We are assigning this string to the variable
message using the assignment operator (=).
Python’s assignment operator assigns the value on its right to the variable on its left.
Printing an integer
Using the same syntax we have used in the previous section, you can assign the value 42 (an integer) to the variable
number = 42
Printing a list
Now let’s see how to print a list in Python. Once again the syntax is the same you have seen previously, with the assignment operator used to assign the list [1, 2, 3] to the variable
Note: We are using the plural in the variable name to show that this is a list (it contains multiple values). This is a way to make your code more readable because this naming convention immediately reminds you that you are working with a variable that contains multiple values.