# Python 如何列印出多個變數

Jinku Hu 2023年1月30日

## 需求

``````city = "Amsterdam"
country = "Netherlands"
``````

``````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+ 新引入的方法

``````# Only from Python 3.6
>>> print(f"City {city} is in the country {country}")
``````

DelftStack.com 創辦人。Jinku 在機器人和汽車行業工作了8多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景，但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。