name = \’Zed A. Shaw\’
age = 35
height = 74
inch_to_cm = 2.54
pound_to_kg = 0.45359
weight = 180
height_cm = height * inch_to_cm
weight_kg = weight * pound_to_kg
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 heavy.\” % weight
print \”================================\”
print \”He\’s %.2f cms tall.\” % height_cm
print \”He\’s %.2f kgs heavy.\” % weight_kg
print \”================================\”
print \”Actually that\’s not too heavy.\”
print \”He\’s got %s eyes and %s hair.\” % (eyes, hair)
print \”His teeth are usually %s depending on the coffee.\” % teeth
print \”If i add %d, %d, and %d I get %d.\” % (age, height, weight, age + height + weight)
print \”test %r .\” % 45
格式化字符用于控制输出的格式,一般用%加一个类型符对字符串进行格式化。如上面%s, %d
在一串字符中出现格式化字符相当于告诉python,“嘿,我这里预留一个位置给后面的变量,让它以我的格式来输出”。
后面跟多个变量时用括号括起,中间以逗号分隔,按格式化字符的先后顺序填充到相应的位置。如
print \”He\’s got %s eyes and %s hair.\” % (eyes, hair)
%[(name)][flags][width].[precision]typecode
(name)为命名
flags可以有+,-,\’ \’或0。+表示右对齐。-表示左对齐。\’ \’为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。
width表示显示宽度
precision表示小数点后精度
如:
print \”He\’s %.2f cms tall.\” % height_cm
上面浮点型变量height_cm输出时将保留两位小数。
格式符为真实值预留位置,并控制显示的格式。格式符可以包含有一个类型码,用以控制显示的类型,如下:
%s 字符串 (采用str()的显示)
%r 字符串 (采用repr()的显示)
%c 单个字符
%b 二进制整数
%d 十进制整数
%i 十进制整数
%o 八进制整数
%x 十六进制整数
%e 指数 (基底写为e)
%E 指数 (基底写为E)
%f 浮点数
%F 浮点数,与上相同
%g 指数(e)或浮点数 (根据显示长度)
%G 指数(E)或浮点数 (根据显示长度)
%% 字符\”%\”