字符串格式化

来源:互联网 发布: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(数组)之间,有一个%号分隔,它代表了格式化操作



阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 库伯 血轮眼美瞳 neo美瞳 海昌隐形眼镜 neo隐形眼镜 库克 库克手串 库克船长 库克医疗 库克橱柜 库克年薪 库克佛珠 库克男友 库克出柜 库克拜年 库克首谈iphone11降价 库克谈iphone降价 库克回应新iphone不支持5g 库克回应iphone降价效果 库克首谈11降价 库克年终奖1200万美元 库克回应中国区iphone降价 库克手串盘玩后图片 库克回应新iphone太贵 库克念珠是什么 kuke 蒂姆库克 库克念珠 库兰的焰影剑 库区 长江三峡库区昆虫 库卡 库哈 库因 库因克 库奇 库奇出装 库奇品牌logo 库奇品牌标志 外星装甲库奇 英勇投弹手