一 主要语法
在这个练习中我用了一个“函数”(function)来把 formatter 变量变成其他字符串。当你看到我写 formatter.format(...) 时,我就是在告诉 Python 做如下的事情:
- 在第一行定义 formatter 字符串。
- 调用 format 函数,类似于让它来做一个名为 format 的命令行命令。
- 把 4 个参数传给 format ,分别对应 formatter 变量中的 4 个 {} ,就像把参数传给命令行命令 format 一样。
- 为 formatter 变量调用 format 函数的结果就是,一个新的字符串会用四个变量取代原来的 {} ,然后再被打印出来。
二 注意事项
1 为什么one要用引号,而 True 或者 False 却不用? Python 把 True 和 False 当成代表“对“和”错“的关键词。如果你给它们加引号,它们就会变成字符串而无法工作。
2 我能用 IDLE 来运行代吗? 不,你得学着用命令行。它对学习编程非常重要,并且是一个很好的起点。当你继续往下学这本书,你就会发现 IDLE 不管用了。
三 代码及运行结果
1 代码
- 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"
- ))
2 运行结果
- PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay> python ex8.py
- 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
练习8--打印打印
原文:https://www.cnblogs.com/luoxun/p/13177563.html