笨方法学Python 习题 6: 字符串(string)和文本

来源:互联网 发布:推荐算法工程师 编辑:程序博客网 时间:2024/05/29 05:06
#!usr/bin/python# -*- coding:utf8 -*-x = "There are %d types of people." %10binary = "binary"do_not = "don't"y = "Those who know %s and those who %s." % (binary , do_not)print (x)print (y)print ("I said: %r." % x)print ("I alos said: '%s'." % y)hilarious = Falsejoke_evaluation = "Isn't that joke so funny?! %r"print (joke_evaluation % hilarious)w = "This is the left side of ..."e = "a string with a right side."print (w + e) 

运行结果如下:

$ python ex6.pyThere are 10 types of people.Those who know binary and those who don't.I said: 'There are 10 types of people.'.I also said: 'Those who know binary and those who don't.'.Isn't that joke so funny?! FalseThis is the left side of...a string with a right side.$


加分习题

①通读程序,在每一行的上面写一行注解,给自己解释一下这一行的作用。

②找到所有的”字符串包含字符串”的位置,总共有四个位置。

y,print (joke_evaluation % hilarious),print ("I said: %r." % x),print ("I alos said: '%s'." % y)

③你确定只有四个位置吗?你怎么知道的?没准我在骗你呢。


④解释一下为什么 w 和 e 用 + 连起来就可以生成一个更长的字符串。


常见问题回答

%r 和 %s 有什么不同?

%r 用来做 debug 比较好,因为它会显示变量的原始数据(raw data),而其它的符号则是用来向用户显示输出的。

既然有 %r 了,为什么还要用 %s 和 %d?

%r 用来 debug 最好,而其它格式符则是用来向用户显示输出的。

如果你觉得很好笑,可不可以写一句 hilarious = True?

可以。在习题 27 中你会学到关于布尔函数的更多知识。

为什么你在有些字符串上用了 ‘ (单引号) 而在别的上没有用?

很大程度上只是个风格问题,我的风格就是在双引号的字符串中使用单引号。看看第 10 行。g that.

错误 TypeError: not all arguments converted during string formatting。

确定每一行代码都完全正确。这里是因为你的字符串里的 % 格式化字符数量比后面给的变量多,仔细检查一下哪里写错了。


原创粉丝点击