Python: How to Print Variables in a String — CODEFATHER

Claudio Sabato
6 min readNov 15, 2023

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!"
print(message)

The variable 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.

Output:

Hello, World!

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.

number = 42
print(number)

Output

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

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.

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.