Python3打印字符串格式化
问题描述:
是把它推荐给格式化字符串:Python3打印字符串格式化
var = 'python 3'
print(f"This is {var}") # prints out This is python 3
或
var = 'python 3'
print("This is", var)
或旧的字符串格式化
var = 'python 3'
print("This is %s" % var)
而且,是print(f"{var}")
新功能python 3.6?在python 3.5.3中运行相同的代码时,我得到了SyntaxError: invalid syntax
。
答
它是推荐...
没有人执行什么。选择你喜欢的任何选项(第二个打印实际上不是格式化,它只是传递更多的参数来打印)。
f
- 引入了字符串来解决其他格式化方法的一些缺点(请参阅Rational of PEP 498),如果您发现其他方法正常工作,则不需要切换。
是
print(f"{var}")
一个新功能到Python 3.6
是,f
-strings是Python的>= 3.6
。
答
如果您寻找件事要告诉你最好格式化实践尝试使用风格指南像PEP8 print("This is {:s}".format(var)
此处是指它https://www.python.org/dev/peps/pep-0008/
是,[F-字符串(https://www.python.org/dev/peps/pep-0498 /)在3.6中是新增的 – khelwood
*“它是python 3.6的一个新功能吗?”* - [yes](https://docs.python.org/3.6/whatsnew/3.6的.html#PEP-498格式的字符串,文字)。 – jonrsharpe
当我在3.5.2中使用[在线编译器](https://repl.it/languages/python3)运行它时,输出打印时没有错误,所以我很困惑。 – Ricek