Python如何打印出多个变量

我们会在本贴士中来介绍在Python2和3中如何打印出多个变量,或者说如何来构造包含多个变量的字符串。

需求

假设你有两个变量,

city = "Amsterdam"
country = "Netherlands"

请打印出包含这两个变量citycountry的字符串,示例如下,

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))