字符串是非常好用的东西,所以在这个练习中你将学会如何创建包含变量内容的字符串,并使用专门的格式化(format string)和语法把变量的内容放到字符串里,相当于告诉python:“这是一个格式化字符串,把这些变量放到指定的位置!”
代码如下:
# coding: utf-8
__author__ = 'www.py3study.com'
my_name = 'Zed A. Shaw'
my_age = 38
my_height = 74
my_weight = 180
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print("Let's talk about {}".format(my_name))
print("He's {} inches tall.".format(my_height))
print("He's {} pounds heavy.".format(my_weight))
print("Actually that's not too heavy.")
print("He's got {0} eyes and {1} hair.".format(my_eyes, my_hair))
print("His teeth are usually {} depending on the coffee.".format(my_teeth))
# this line is tricky, try to get it exactly right
print("If I add {},{} and {} I get {}.".format(my_age, my_height, my_weight, my_age + my_weight + my_height))
PS:
如果使用了非ASCII字符而且碰到了编码错误,记得在最顶端加一行 # coding: utf-8
应该看到的结果
Let's talk about Zed A. Shaw
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 38,74 and 180 I get 292.
常见问题
这样定义变量行不行: 1 = 'Sam'?
不行.1不是一个有效的变量名称,变量名称要以字母开头,可以是a1,但1不行
.format是什么?%d,%s,%r是什么?
后面会经常用到,.format和%d,%s,%r这些都是“格式控制工具”,它们会告诉python把右边的变量带到字符串中,并且把变量值放到{}所在的位置上,.format是python3的语法
%d,%s,%r是python2的格式化方法,看个列子
print("Let's talk about %s" % my_name),语法上有区别