字符串格式化
来源:互联网 发布:rpg游戏源码 编辑:程序博客网 时间:2024/06/14 10:11
作为IT人士,只有不断地学习新知识才不会被淘汰,从今天开始学习Python,《笨方法学习Python》希望CSDN能监督我能完整学习这门语言,觉得需要记录的就会在博客记录。
my_name = 'YeLing'my_age = 33my_height = 158my_weight = 105my_eyes = 'black'my_teeth = 'White'my_hair = 'black'print "Let's talk about %s." % my_nameprint "She's %d cm tall." % my_heightprint "She's %d pounds heavy." % my_weightprint "Actually that's not too heavy."print "She's got %s eyes and %s hair." % (my_eyes, my_hair)print "Her teeth are usually %s depending on the coffee." % my_teethprint "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
输出为:
Let's talk about YeLing.She's 158 cm tall.
She's 105 pounds heavy.
Actually that's not too heavy.
She's got black eyes and black hair.
Her teeth are usually White depending on the coffee.
If I add 33, 158, and 105 I get 296.
其中格式化用到 “%”操作符
格式化字符串时,Python使用一个字符串作为模板。模板中有格式符,这些格式符为真实值预留位置,并说明真实数值应该呈现的格式。Python用一个tuple将多个值传递给模板,每个值对应一个格式符。
比如下面的例子:
print "Let's talk about %s." % my_name
print "She's got %s eyes and %s hair." % (my_eyes, my_hair)
上面的例子中,
"She's got %s eyes and %s hair." 为我们的模板。%s为第一个格式符,表示一个字符串。(my_eyes, my_hair)的两个元素my_eyes, my_hair为替换%s和%s的真实值。
在模板和tuple(数组)之间,有一个%号分隔,它代表了格式化操作。
阅读全文