How to print multiple arguments in Python
We will show you how to print multiple arguments in Python 2 and 3.
Requirement
Suppose you have two variables
city = "Amsterdam"
country = "Netherlands"
Please print the string that includes both arguments city
and country
, like below
City Amsterdam is in the country Netherlands
Solutions - Print multiple arguments in Python
Python 2 and 3 Solutions
1. Pass values as parameters
# Python 2
>>> print "City", city, 'is in the country', country
# Python 3
>>> print("City", city, 'is in the country', country)
2. Use string formatting
There are three string formatting methods that could pass arguments to the string.
- Sequential option
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
- Formatting with numbers
The advantages of this option compared to the last one is that you could reorder the arguments and reuse some arguments as many as possible. Check the examples below,
# Python 2
>>> print "City {1} is in the country {0}, yes, in {0}".format(country, city)
# Python 3
>>> print("City {1} is in the country {0}, yes, in {0}".format(country, city))
- Formatting with explicit names
# Python 2
>>> print "City {city} is in the country {country}".format(country=country, city=city)
# Python 3
>>> print("City {city} is in the country {country}".format(country=country, city=city))
3. Pass arguments as a tuple
# Python 2
>>> print "City %s is in the country %s" %(city, country)
# Python 3
>>> print("City %s is in the country %s" %(city, country))
Python 3.6 Only Method - f-string formatting
Python introduces a new type of string literals-f-strings
from version 3.6. It is similar to the string formatting method str.format()
.
# Only from Python 3.6
>>> print(f"City {city} is in the country {country}".format(country=country, city=city))