【发布时间】:2020-04-27 08:38:15
【问题描述】:
我注意到,当 not 包含在 print() 函数中时,从 Python 控制台运行带有转义字符的 f 字符串的行为会有所不同。例如,包装在 print() 函数中,\n 会按预期运行:
>>>a = 1
>>>b = 'frog'
>>>c = 3
>>>print(f"""The first variable is {a}\nThe second is {b} and the third is {c}""")
The first variable is 1
The second is frog and the third is 3
直接运行,它的作用不同,将\n 打印为文本。
>>>f"""The first variable is {a}\nThe second is {b} and the third is {c}"""
'The first variable is 1\nThe second is frog and the third is 3'
我的问题是:这种行为变化的根本原因是什么?在其他情况下(例如在查询、写入文本文件等)中使用这种格式化字符串时可能需要注意什么? ?
【问题讨论】:
-
我发现@APhillips 引用的帖子并没有回答我的问题,主要是因为我没有尝试将字符放在花括号内,我看到
\n字符在大括号之外大括号在输出中被完美格式化。那时我还没有理解 print() 语句的意义。尽管@John Kugelman 支持 Monica 的引用链接确实回答了这个问题(因此得到了赞成),但它并没有出现在搜索中,原因是转义字符\n没有在控制台中呈现为回车符。跨度>
标签: python python-3.x string formatting