习题 5: 更多的变量和打印
ex5.py
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
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 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 coffee." %my_teeth
# this line is tricky, try to get itexactly right
print "If I add %d, %d, and %d I get %d." %(
my_age, my_height, my_weight, my_age + my_height + my_weight)
总结:
字符串格式化
格式 | 描述 |
%% | 百分号标记 |
%c | 字符及其ASCII码 |
%s | 字符串 |
%d | 有符号整数(十进制) |
%u | 无符号整数(十进制) |
%o | 无符号整数(八进制) |
%x | 无符号整数(十六进制) |
%X | 无符号整数(十六进制大写字符) |
%e | 浮点数字(科学计数法) |
%E | 浮点数字(科学计数法,用E代替e) |
%f | 浮点数字(用小数点符号) |
%g | 浮点数字(根据值的大小采用%e或%f) |
%G | 浮点数字(类似于%g) |
%p | 指针(用十六进制打印值的内存地址) |
%n | 存储输出字符的数量放进参数列表的下一个变量中 |
%r | 字符串 (采用repr()的显示) |
自我测试:
ex5.1.py
tt =13.555
my_weight = 170 # lib
pounds = 0.453 *my_weight
print "you have %6.2f apples" %tt
print "you have %3.2f apples" %tt
print "you have %2.1f apples" %tt
print "you have %1.1f apples" %tt
print "you are %d pounds or %3.3f kg heavy." %(my_weight,pounds)
习题 6: 字符串(string) 和文本
ex6.py
x ="There are %d types ofpeople." % 10
binary = "binary"
do_not = "don't"
y ="Those who know %s andthose who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w ="This is the left side of..."
e =" a string with a rightside."
print w +e
运行结果:
Ex6_1.py (个人注释理解)
#-*- coding:utf-8 -*-
x = "Thereare %d types of people." % 10 #将右边双引号的赋值给x,将10格式化输出(有符号整数)
binary = "binary" #将binary赋值给binary
do_not = "don't" #将don't 赋值给 do_not
y = "Thosewho know %s and those who %s." % (binary,do_not) #将右边双引号的赋值给y,分别将binary,do_not格式化输出(字符串)
print x
print y
print "Isaid: %r." %x #此处前面好理解,但是原x的双引号成了单引号我需要再查查原因。
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
printjoke_evaluation % hilarious #两者对比还是有区别的。
print joke_evaluation,hilarious
w = "Thisis the left side of ..." #此处后者存在一个空格
e =" a string with a rightside."
print w +e
print w ,e