ID : 135
viewed : 97
Tags : PythonPython Print
92
We will show you how to print multiple arguments in Python 2 and 3.
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
# Python 2 >>> print "City", city, 'is in the country', country # Python 3 >>> print("City", city, 'is in the country', country)
There are three string formatting methods that could pass arguments to the string.
# Python 2 >>> print "City {} is in the country {}".format(city, country) # Python 3 >>> print("City {} is in the country {}".format(city, country))
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))
# 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))
# 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 introduces a new type of string literals- 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))