In Python, the print() function allows you to print multiple values by separating them with commas (,) or concatenation (+). Here’s how:
Commas automatically add spaces between values.
name = "John"
age = 25
city = "New York"
print("Name:", name, "Age:", age, "City:", city)Name: John Age: 25 City: New York
✔ No need to convert data types (e.g., int to str).
✔ Automatically adds spaces between values.
name = "John"
age = 25
print("Name: " + name + ", Age: " + str(age)) # Need str() conversionName: John, Age: 25
⚠ Issue: You must manually convert int to str using str(age).
name = "John"
age = 25
city = "New York"
print(f"Name: {name}, Age: {age}, City: {city}")Name: John, Age: 25, City: New York
✔ Best method for clean and readable formatting.
✔ No need for explicit type conversion.
print("Name: {}, Age: {}, City: {}".format(name, age, city))Name: John, Age: 25, City: New York
✔ Works in older Python versions (<3.6).
❌ Less readable than f-strings.
You can modify the default space separator.
print(name, age, city, sep=" | ")John | 25 | New York
✔ Use sep for custom formatting (e.g., commas, pipes, dashes).
By default, print() ends with a newline (\n). You can change this using end="".
print("Hello", end=" ")
print("World!") # Prints on the same lineHello World!
my_list = [1, 2, 3, 4, 5]
print("List values:", *my_list) # Unpacks list elementsList values: 1 2 3 4 5
✔ Using *list unpacks elements, separating them with spaces.
| Method | Description |
|---|---|
print(a, b, c) |
Adds spaces automatically between values (Best for most cases). |
print("Hello " + str(num)) |
Concatenation (Manual type conversion needed). |
print(f"Value: {x}") |
Best readability (f-strings). |
print("Value: {}".format(x)) |
Alternative formatting (older versions). |
print(a, b, c, sep=", ") |
Custom separator (comma, pipe, etc.). |
print(a, end=" ") |
Print without newline (continuous printing). |
print(*my_list) |
Unpack and print list elements. |
🚀 Best Practice: Use f-strings (f"{variable}") for clean and readable formatting.