8.打印,打印——.format()
前言
对字符串做更复杂的格式化。
一、Atom文本编辑器
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"
))
这里用到了一个叫函数(function)的东西,让它返回formatter变量到其他字符串中。程序里的formatter.format(…)让Python做了以下操作:
(1) 取第1行定义的formatter字符串。
(2) 调用它的format函数,相当于让它执行一个叫做format的命令行命令。
(3) 给format传递4个参数,这些参数和formatter变量中的{ }匹配,相当于将参数传递给了format这个命令。
(4) 在formatter上调用format的结果是一个新的字符串,其中的{ }被4个变量替换掉了,这就是print现在打印出来的结果。
二、运行Python程序
在Window上键入Python就可以看到结果。
python ex8.py
总结
以上内容介绍了Python中的字符串和文本的用法,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。