习题 5: 更多的变量和打印
我们现在要键入更多的变量并且把它们打印出来。这次我们将使用一个叫“格式化字符串(format string)”的东西. 每一次你使用 " 把一些文本引用起来,你就建立了一个字符串。字符串是程序将信息展示给人的方式。你可以打印它们,可以将它们写入文件,还可以将它们发送给网站服务器,很多事情都是通过字符串交流实现的。字符串是非常好用的东西,所以再这个练习中你将学会如何创建包含变量内容的字符串。使用专门的格式和语法把变量的内容放到字符串里,相当于来告诉 python :“嘿,这是一个格式化字符串,把这些变量放到那几个位置。”一样的,即使你读不懂这些内容,只要一字不差地键入就可以了。
python2:
my_name = 'Zed A. Shaw' my_age = 35 # not a liemy_height = 74 # inchesmy_weight = 180 # lbsmy_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown'
print "Let's talk about %s." % my_nameprint "He's %d inches tall." % my_heightprint "He's %d pounds heavy." % my_weightprint "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair)print "His teeth are usually %s depending on the coffee." % my_teeth# this line is tricky, try to get it exactly rightprint "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight)
Warning
如果你使用了非 ASCII 字符而且碰到了编码错误,记得在最顶端加一行 # -- coding: utf-8 -- 。
你应该看到的结果:

Python3:
my_name = 'Zed A. shaw'my_age = 35 # not a liemy_height = 74 # inchesmy_weight = 180 # lbsmy_eyes = 'Blue'my_teeth = 'White'my_hair = 'Brown'
print ("Let's talk about %s." % my_name)print ("He's %d inches tall." % my_height)print ("He's %d pounds heavy." % my_weight)print ("Actually that's not too heavy.")print ("He's got %s eyes and %s hair." % (my_eyes,my_hair))print ("His teeth are usually %s depending on the coffe." % my_teeth)# this line is tricky,try to get it exactly rightprint ("If I add %d, %d, and %d I get %d." % (my_age,my_height,my_weight,my_age + my_height + my_weight))
得到的结果为:
这里使用了大量的格式化输出,关于格式化输出我本打算整理一下,结果发现网上已经有前辈做了整理,比我自己写的好多了,这里给大家贴两个链接:
Python格式化输出 - MindProbe - 博客园
加群交流在后台回复“加群”,添加小编微信,小编拉你进去猜您喜欢往期精选▼笨办法学 Python--跟书练习一
笨办法学 Python--跟书练习二
笨办法学 Python--跟书练习三
小白学 Python(1):开篇
小白学 Python(2):基础数据类型(上)
小白学 Python(3):基础数据类型(下)
小白学 Python(4):变量基础操作
用 Python 一键分析你的上网行为,看是在认真工作还是摸鱼
Python安装及环境配置
Python语法入门(一)
Python入门网络爬虫之精华版
END
更多资源尽在星球,后台回复“星球”获取优惠