习题 5: 更多的变量和打印(学会如何创建包含变量内容的字符串。)
在文本编辑器中,编辑以下内容并保存到ex5.py文件中,同时在终端中运行该文件:
my_name = 'Zed A. Shaw'
my_age = 35
my_height = 74
my_weight = 180
my_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 heavey." % my_weight
print "Actually that's not too heavy"
print "He's got %s eyes and %s hair." %(my_eyes,my_hair)
print "He's teeth are usually %s depending on the coffee." % my_teeth
#this line is tricky, try to get it actualy right
print "If I add %d, %d, and %d, I get %d." %(my_age, my_height,my_weight,my_age+my_height+my_weight)
执行结果:
加分习题:
- 修改所有的变量名字,把它们前面的
my_
去掉。确认将每一个地方的都改掉,不只是你使用=
赋值过的地方。
name = 'Zed A. Shaw'
age = 35
height = 74
weight = 180
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavey." % weight
print "Actually that's not too heavy"
print "He's got %s eyes and %s hair." %(eyes,hair)
print "He's teeth are usually %s depending on the coffee." % teeth
#this line is tricky, try to get it actualy right
print "If I add %d, %d, and %d, I get %d." %(age, height,weight,age+height+weight)
执行结果:
- 试着使用更多的格式化字符。例如 %r 就是是非常有用的一个,它的含义是“不管什么都打印出来”。
%s,获取传入对象的str方法的返回值,并将其格式化到指定位置
%r,获取传入对象的repr方法的返回值,并将其格式化到指定位置
%d,将整数、浮点数转换成十进制表示,并将其格式化到指定位置
下面对比一下这三者在处理不同数据类型时的区别
(1)处理int类型
print "I am %d years old." % 22
print "I am %s years old." % 22
print "I am %r years old." % 22
执行结果:
(2)处理字符串
text = "I am %d years old." % 22
print "I said: %s." % text
print "I said: %r." % text
执行结果:
(3)处理时间类型
import datetime
d = datetime.date.today()
print "%s" % d
print "%r" % d
执行结果:
参考博客:https://blog.csdn.net/wusuopuBUPT/article/details/23678291
- 在网上搜索所有的 Python 格式化字符。
参考博客:https://blog.csdn.net/JuneLembert/article/details/88093823 - 试着使用变量将英寸和磅转换成厘米和千克。不要直接键入答案。使用 Python的计算功能来完成。
1英寸(in)=2.54厘米(cm)
1磅(lb)=0.45359237千克(kg)
#-- coding: utf-8 --
my_name = 'Zed A. Shaw'
my_age = 35
my_height = 74*2.54
my_weight = 180*0.45359237
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d cm tall." % my_height
print "He's %d kg heavey." % my_weight
print "Actually that's not too heavy"
print "He's got %s eyes and %s hair." %(my_eyes,my_hair)
print "He's teeth are usually %s depending on the coffee." % my_teeth
#this line is tricky, try to get it actualy right
print "If I add %d, %d, and %d, I get %d." %(my_age, my_height,my_weight,my_age+my_height+my_weight)
执行结果: