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.
numbers = [1, 2, 3]
print(numbers)
Output
[1, 2, 3]
The print() function is a simple yet effective way to show variable values in Python.
Use Concatenation to Print Variables as Part of a String
Concatenation allows you to combine strings and variables to create dynamic messages. You can achieve this using the + operator.
Here’s how it works:
name = "Dan"
age = 33
message = "Hello, my name is " + name + " and I am " + str(age) + " years old."
print(message)
First you create the string variable name
and the integer variable age
. Then you concatenate them to create the string variable message
.
Output
Hello, my name is Dan and I am 33 years old.
In this example, you are combining strings to create a personalized message. Note that you are converting the int variable age
to a string using Python’s str() built-in function for correct concatenation (you would see an error otherwise).
In the example above, can you see how many times we had to use the + (concatenation operator) to create the final message
string?
This is not the best approach to create the final string and in the next section, you will learn a better approach.
Improve the Way You Print Python Variables in a String with f-strings
Python 3.6 introduced a more elegant and efficient way to embed variables in strings: f-strings. F-strings are concise and highly readable, making your code more expressive. To use f-strings, prepend the string with an ‘f’ or ‘F’ and enclose the variable names in curly braces {}.
Here’s an example of how f-strings work:
name = "Dan"
age = 33
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
Have a look at the line of code above to create the message
string. This is a lot cleaner and concise compared to the same line we have seen in the previous section that uses the concatenation operator!
Let’s put them side by side for an easier comparison:
# Concatenation operator
message = "Hello, my name is " + name + " and I am " + str(age) + " years old."
# f-string
message = f"Hello, my name is {name} and I am {age} years old."
Make sure you understand the differences between the two assignment expressions.
Output
Hello, my name is Dan and I am 33 years old.
With f-strings, you can directly embed variable values into your string, eliminating the need for explicit type conversions and concatenation.
Python f-strings vs Concatenation: Which One is Better?
F-strings offer several advantages over concatenation when it comes to displaying variables in strings:
- Readability: f-strings make code more readable by clearly indicating where variables are inserted into the string.
- Efficiency: f-strings are faster than concatenation, especially when dealing with large strings or many variables.
- Type Conversion: f-strings handle type conversion automatically, reducing the risk of errors.
- Expression Evaluation: You can include expressions within f-strings, making them versatile for complex variable embedding.
Take a look at the following code to understand expression evaluation:
# Expression Evaluation Example
result = 4 * 7
message = f"The result of the expression 4 * 7 is {result}."
print(message)
Expression evaluation means that the operation to calculate the value of the variable result
is calculated as part of the f-string.
Output
The result of the expression 4 * 7 is 28.
In most cases, f-strings are the preferred choice for formatting strings with variable values, as they are easier to maintain and less error-prone than concatenation.
Enhancing String Formatting with f-strings
F-strings go beyond basic variable insertion. They allow you to format variables within a string, making your output even more customized.
Here are a few formatting options you can use with f-strings:
- String Alignment: You can control the alignment of your variables within a string. For instance, you can left-align or center-align text. Take a look at the example below:
# String Alignment with f-strings
message = "Hello, World!"
centered_message = f"{message : ^20}"
print(centered_message)
# Output
Hello, World!
The colon character (:) in the expression {message : ^20}
indicates the start of the format specifier. The format specifier ^20
tells Python to center-align the content of the variable message
within a field of 20 characters.
If the content of the string message
is shorter than 20 characters, the extra characters are filled with spaces.
- Number Formatting: When dealing with numerical values, you can specify the number of decimal places, add thousands separators, or format numbers as percentages. You can see an example below:
# Number Formatting with f-strings
amount = 1462.684
formatted_amount = f"Amount: {amount : ,.2f}"
print(formatted_amount)
# Output
Amount: 1,462.68
In the expression {amount : ,.2f}
the comma adds the thousands separator and .2f
rounds the number to 2 decimal places.
- Date and Time Formatting: If you’re working with date and time objects, you can format them according to your requirements. Look at the example below:
# Date and Time Formatting with f-strings
from datetime import datetime
current_date = datetime.now()
formatted_date = f"Current Date: {current_date : %Y-%m-%d %H:%M:%S}"
print(formatted_date)
# Output
Current Date: 2023-11-15 00:05:36
In this example, the expression embedded in the f-string {current_date : %Y-%m-%d %H:%M:%S}
formats the date as YYYY-MM-DD HH:MM:SS.
These formatting options provide you with more control over how your variables are displayed within a string.
Practical Use Cases for Variable Printing
Now that we’ve explored the various techniques for printing variables in strings, let’s consider some practical use cases where these methods come in handy:
- Logging: When developing applications, logging is a crucial tool for monitoring and debugging. Using f-strings, you can log variables along with descriptive messages for better troubleshooting.
- User Interfaces: If you’re building a graphical user interface (GUI) application, f-strings can help you dynamically update text and labels to provide real-time information to users.
- Report Generation: Generating reports often involves inserting variable data into predefined templates. F-strings simplify this process by allowing you to easily inject variable values into report templates.
Conclusion
In Python, there are various ways to print variables in a string, with the print() function, concatenation, and f-strings at your disposal. While all methods have merits, f-strings offer the most efficient and readable approach for displaying variable values within strings.
As a beginner developer, mastering f-strings will not only enhance your Python skills but also improve the quality and maintainability of your code.
This knowledge will serve you well in a wide range of programming scenarios, from simple scripts to complex applications, and help you communicate effectively through your code.
Claudio Sabato is an IT expert with over 15 years of professional experience in Python programming, Linux Systems Administration, Bash programming, and IT Systems Design. He is a professional certified by the Linux Professional Institute.
With a Master’s degree in Computer Science, he has a strong foundation in Software Engineering and a passion for robotics with Raspberry Pi.