Skip to main content
 首页 » 编程设计

python之艰难地学习 Python,练习 6。

2025年05月04日14lonelyxmas

我搜索了该站点,但似乎以前的问题中没有涵盖《艰难地学习 Python》一书中的这个练习。

我有这个练习:

1)找出一个字符串在一个字符串中的所有位置。有四个地方。 2)你确定只有四个地方吗?你怎么知道?也许我喜欢说谎。

x = "There are %d types of people." % 10 
binary = "binary" 
do_not = "don't" 
y = "Those who know %s and those who %s." % (binary, do_not) #two strings inside a string, count is 2 
 
print x 
print y 
 
print "I said: %r." % x #here, count is 3 
print "I also said: '%s'." % y #here, count is 4 
 
hilarious = False 
joke_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 

我试图解决它并评论了我在字符串中找到字符串的行(found4)。但是,作者的第二个问题让我担心我还没有找到全部。我错过了什么吗?如果是的话,你能告诉我什么吗?

请您参考如下方法:

如果您将“将字符串放在字符串中”解释为“使用带有字符串参数的格式字符”,那么您正确地识别了所有这四次出现。收起无用的说明并解释发生了什么可能会更有帮助。有关更多信息,请查看 offical documentation for formatting characters .我会尽量包含一些有用的练习,而不是技巧性的问题。

x = "There are %d types of people." % 10 

%d 是 Signed integer decimal 的格式化字符(大多数人在听到“数字”时会想到的)。 10用十进制表示并插入到字符串中,得到字符串There are 10 types of people.。

练习:"7+6: %d"% (7+6) 会产生什么结果?在您的 Python shell 中对其进行测试。
练习:"0x12: %d"% 0x12 会产生什么结果?在您的 Python shell 中测试它。 提示:前缀0x 表示后面的数字是hexadecimal ,即基数 16 而不是 10。

binary = "binary" 
do_not = "don't" 
y = "Those who know %s and those who %s." % (binary, do_not) 

%s 插入值的字符串表示形式。这个例子表明,如果格式字符串中有多个 %d、%s 左右,我们需要在 < em>元组 或列表。元组 (round, braces) 和列表 [square, braces] 之间的区别在于元组是不可变的(即不能更改),但列表可以。

练习:给定元组 x = ('world', 'Hello'),构造一个具有正确顺序的元组 y字。 Dive Into Python's introduction of tuples将帮助您了解元组的基础知识。

print "I said: %r." % x 

%r 是一个值的表示,理想情况下您可以将其输入到 Python shell 中。您可以使用 repr 获得相同的表示形式功能。例如,repr("a") == "'a'",而 str(a) == "a"。对于除字符串之外的大多数类型,repr 和 str 的结果(或格式字符串中的 %r 和 %s ) 是一样的。

print w + e 

这连接两个字符串(即一个接一个地放置)。请注意,如果两个参数都是数字,则 + 表示其他内容(加法)。

练习:“3”+“4”的结果是什么?在您的 Python shell 中对其进行测试。
练习:给定 x = "3"; y = "4",打印出总和 7 ( Hint )。