笨方法学python-2(习题6-9)

做个勤劳的填坑人


习题六:字符串和文本

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

x = "There are %d type of people." % 10     # 定义一个格式化字符串
binary = "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)   # 把x作为参数传递给字符串打印
print("I also said: '%s'." % y)   # 把y作为参数传递给字符串打印

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)    # 打印合并两个字符串


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

y = "Those who know %s and those who %s." % (binary, do_not)
print("I said : %r." % x)
print("I also said: '%s'." % y)
joke_evaluation = "Isn't that joke so funny?! %r" 
3. 你确定只有四个位置吗?你怎么知道的?没准我在骗你呢。
4. 解释一下为什么  w 和  e 用  + 连起来就可以生成一个更长的字符串。

因为w和e都是字符串,有博客说是调用了jion的方法。如果是两个数值的话,+最后就是加法运算的结果


扫描二维码关注公众号,回复: 1854658 查看本文章

习题七:更多打印

1. 逆向阅读,在每一行的上面加一行注解。
2. 倒着朗读出来,找出自己的错误。
3. 从现在开始,把你的错误记录下来,写在一张纸上。
4. 在开始下一节习题时,阅读一遍你记录下来的错误,并且尽量避免在下个练习中再犯同样的错误。
5. 记住,每个人都会犯错误。程序员和魔术师一样,他们希望大家认为他们从不犯错,不过这只是表象而已,他们每时每刻都在犯错。

print("Mary had a little lamd.")
print("Its fleece was white as %s." % 'snow')
print("And everywhere that Mary went.")
print("." * 10)

end1 = "c"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

print(end1+end2+end3+end4+end5+end6,end=" ")
print(end7+end8+end9+end10+end11+end12)




习题八:打印,打印


formatter = "%r %r %r %r"
print(formatter % (1, 2, 3, 4))
print(formatter % ("one", "two", "three", "four"))
print(formatter % (True, False, False, True))
print(formatter % (formatter, formatter, formatter,formatter))
print(formatter %(
    "I had this thing.",
    "That you could type up right.",
    "Nut it didn't sing.",
    "So I said goodnight"
))

1.  自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。
2. 注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?

查了一下单引号双引号的问题:字符串中既可以有单引号也可以有双引号,单引号可以括双引号,双引号可以括单引号;单不能扩单,双不能括双

之所以在输出的时候有单引号是因为引用字符%r,上面参考博文python中%r和%s的区别里对%s和%r的区别分析的很清楚。

%r打印可以重现它代表的对象。


习题九:打印、打印、打印

1.  自己检查结果,记录你犯过的错误,并且在下个练习中尽量不犯同样的错误。


days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFed\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days: ", days)
print("Here are the months: ", months)
print("""
There's something going on here.
With the three double-quotes.
we'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")



猜你喜欢

转载自blog.csdn.net/jesmine_gu/article/details/80791265