In this tutorial, you will learn how to print numbers in a string using Python. This is especially useful when you are dealing with variables that are both strings and integers, and need to display the output in a formatted manner.
We will go through various methods to achieve the desired results, such as string concatenation, f-strings, and the format()
function.
Step 1: Using string concatenation
One way to print numbers in a string is by using string concatenation. To do this, we can simply convert the integer to a string using the str()
function and then concatenate the two strings using the +
operator.
number = 42
text = “The answer to life, the universe, and everything is: “
result = text + str(number)
print(result)
Step 2: Using f-strings (Python 3.6+)
Starting from Python 3.6, f-strings (formatted string literals) were introduced. F-strings provide a simple and efficient way to embed expressions inside string literals, using curly braces {}
.
To use f-strings, you can place an f
or F
in front of the string, and then use curly braces to enclose the variable you want to include in the string. Let’s see an example of how to use f-strings to print numbers in a string.
1 2 3 |
number = 42 result = f"The answer to life, the universe, and everything is: {number}" print(result) |
Step 3: Using the format()
function
Another way to print numbers in a string is by using the format()
function. Like f-strings, the format()
function can embed variables inside strings by placing placeholders inside the string, and then passing the variables to the format()
function as arguments.
Here’s how you can print numbers in a string using the format()
function:
1 2 3 4 5 |
number = 42 text = "The answer to life, the universe, and everything is: {}" result = text.format(number) print(result) |
Full code
Below is the full code for all the methods discussed above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
## String concatenation number = 42 text = "The answer to life, the universe, and everything is: " result = text + str(number) print(result) ## F-strings number = 42 result = f"The answer to life, the universe, and everything is: {number}" print(result) ## format() function number = 42 text = "The answer to life, the universe, and everything is: {}" result = text.format(number) print(result) |
Output
The answer to life, the universe, and everything is: 42 The answer to life, the universe, and everything is: 42 The answer to life, the universe, and everything is: 42
Conclusion
In this tutorial, we learned three different ways to print numbers in a string using Python – string concatenation, f-strings, and the format()
function. Each method has its benefits, and you can choose the one that best suits your needs. If you have Python 3.6 or newer, f-strings are generally preferred because of their simplicity and efficiency.