前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >习题5:更多的变量和打印

习题5:更多的变量和打印

作者头像
py3study
发布2018-08-02 10:49:57
4860
发布2018-08-02 10:49:57
举报
文章被收录于专栏:python3

字符串是非常好用的东西,所以在这个练习中你将学会如何创建包含变量内容的字符串,并使用专门的格式化(format string)和语法把变量的内容放到字符串里,相当于告诉python:“这是一个格式化字符串,把这些变量放到指定的位置!”

代码如下:

代码语言:javascript
复制
# coding: utf-8
__author__ = 'www.py3study.com'
my_name = 'Zed A. Shaw'
my_age = 38
my_height = 74
my_weight = 180
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'

print("Let's talk about {}".format(my_name))
print("He's {} inches tall.".format(my_height))
print("He's {} pounds heavy.".format(my_weight))
print("Actually that's not too heavy.")
print("He's got {0} eyes and {1} hair.".format(my_eyes, my_hair))
print("His teeth are usually {} depending on the coffee.".format(my_teeth))
# this line is tricky, try to get it exactly right
print("If I add {},{} and {} I get {}.".format(my_age, my_height, my_weight, my_age + my_weight + my_height))

PS:

如果使用了非ASCII字符而且碰到了编码错误,记得在最顶端加一行 # coding: utf-8

应该看到的结果

Let's talk about Zed A. Shaw He's 74 inches tall. He's 180 pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 38,74 and 180 I get 292.

常见问题

这样定义变量行不行:    1 = 'Sam'?

不行.1不是一个有效的变量名称,变量名称要以字母开头,可以是a1,但1不行

.format是什么?%d,%s,%r是什么?

后面会经常用到,.format和%d,%s,%r这些都是“格式控制工具”,它们会告诉python把右边的变量带到字符串中,并且把变量值放到{}所在的位置上,.format是python3的语法

%d,%s,%r是python2的格式化方法,看个列子

print("Let's talk about %s" % my_name),语法上有区别

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档