Python如何列印出多個變數
我們會在本貼士中來介紹在Python2和3中如何列印出多個變數,或者說如何來構造包含多個變數的字串。
需求
假設你有兩個變數,
city = "Amsterdam"
country = "Netherlands"
請列印出包含這兩個變數city
和country
的字串,示例如下,
City Amsterdam is in the country Netherlands
解決方案
Python2及3的方法
1. 傳遞引數的值
# Python 2
>>> print "City", city, 'is in the country', country
# Python 3
>>> print("City", city, 'is in the country', country)
2. 格式化字串
格式化字串中,有三種可以傳遞引數的方法,
- 順序傳遞
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
- 建立數字索引
這種方式同上一種方式相比,優點是傳遞引數的時候你可以對引數進行重新排序,而且假如引數被多次引用的話,你只需要在引數列表中輸入一次。
# 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))
3. 多個引數組成元組來傳遞引數
# Python 2
>>> print "City %s is in the country %s" %(city, country)
# Python 3
>>> print("City %s is in the country %s" %(city, country))
Python3.6+新引入的方法
從Python3.6開始有了新的一種格式化字串的方法-f-strings
。 它有點類似於字串格式化方法str.format()
.
# Only from Python 3.6
>>> print(f"City {city} is in the country {country}".format(country=country, city=city))