In Python, when you use the print
function, it automatically prints the output on a new line. However, there might be situations where you need to print multiple values on the same line. In this tutorial, we will learn different ways to achieve this in Python.
Method 1: Using the ‘end’ parameter
Python’s print
function has a parameter called end
, which determines what string is printed at the end of the line. By default, the end
parameter is set to a newline character (\n
). We can change the value of the end
parameter to print on the same line.
Consider the following example:
1 2 |
print("Hello, ", end="") print("World!") |
Hello, World!
In this example, we set the end
parameter to an empty string in the first print
statement. As a result, the second print
statement continues on the same line right after the first one.
Method 2: Using f-strings (Python 3.6+)
In Python 3.6 and later, f-strings were introduced as a new way of formatting strings. We can use them to concatenate multiple values and print them on the same line.
Here’s an example:
1 2 3 |
name = "John" age = 30 print(f"My name is {name} and I am {age} years old.") |
My name is John and I am 30 years old.
In this example, we use an f-string to embed the values of the name
and age
variables directly into the print statement, ensuring that they are printed on the same line.
Method 3: Using the ‘sep’ parameter
You can also use the sep
parameter in the print
function to define a delimiter between multiple values. By default, the sep
parameter is set to a space character (' '
).
For example:
1 2 3 4 |
a = 1 b = 2 c = 3 print(a, b, c, sep=", ") |
1, 2, 3
In this example, we set the sep
parameter to a comma followed by a space. This causes the print
function to print the values of a
, b
, and c
separated by a comma and a space.
Full code:
1 2 3 4 5 6 7 8 9 10 11 |
print("Hello, ", end="") print("World!") name = "John" age = 30 print(f"My name is {name} and I am {age} years old.") a = 1 b = 2 c = 3 print(a, b, c, sep=", ") |
Conclusion
In this tutorial, we have learned three different ways to print multiple values on the same line in Python: by changing the end
parameter, using f-strings (for Python 3.6+), and using the sep
parameter. Now you can choose the most appropriate method depending on your requirements and the version of Python you are working with.