LearnPython3theHardWay__Excercise 8 Printing,Printing

知识点:字符串的方法format
继续print。下面的代码看起来复杂,不懂就注释,理解后,很简单。

formatter = "{} {} {} {}"

print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
	"Try your",
	"Own text here",
	"Maybe a poem",
	"Or a song about fear"
))

What you should see
1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text here Maybe a poem Or a song about fear

这里用了format方法。前几次练习我们已经接触过。当我们这么使用: formatter.format(…),python在做以下的事情:
1、取出第一行被定义的 formatter
2、调用format这个方法,也可以说执行一个叫format的命令
3、按位置传递format的4个参数给formatter里对应的4个{}
4、调用后,formatter得到了4个参数并被print打印了出来

作者说这里比较烧脑,大家多练习几次吧


Study Drills

检查并记下错误,让这个错误不要再犯

关于format的更详细用法,可看这里:
MOOC —— Python语言程序设计 by 北京交通大学 第一章 概述

猜你喜欢

转载自blog.csdn.net/byakki/article/details/86483046
今日推荐