Python 如何打印出多个变量
Jinku Hu
2023年1月30日
2018年3月4日
我们会在本贴士中来介绍在 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}")
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn