import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
print("x:\n{}".format(x))
print("x:\n",x)
print("x:\n{}".format(x))
和print("x:\n",x)
之间有什么区别?
我不理解print("x:\n{}".format(x))
的概念及其运作方式!
当你说.format指的是什么点?什么是里面的“”?
为什么我们需要{}?
由于
答案 0 :(得分:0)
大括号是包含 “替换”字段that describe to the format engine what should be placed in the output。也就是说,它们是特殊字符,解析器用它来确定如何格式化特定的字符串对象。
如果您的打印功能有多个参数,则实用程序会更清晰:
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[1, 2, 3], [4, 5, 6]])
z = np.array([[1, 2, 3], [4, 5, 6]])
print("x:\n", x, y, z)
输出:
x:
[[1 2 3]
[4 5 6]] [[1 2 3]
[4 5 6]] [[1 2 3]
[4 5 6]]
并且:
print("x:\n{}\n\n{}\n\n{}".format(x, y, z))
输出:
x:
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
甚至:
a_list_of_terms = ['the', 'knights', 'who', 'say', 'ni']
print("{}".format(a_list_of_terms))
输出:
['the', 'knights', 'who', 'say', 'ni']
或者您可以使用*
解压缩列表:
print("We are {} {} {} and we demand a shrubbery.".format(*a_list_of_terms))
输出:
'We are the knights who and we demand a shrubbery.'
您可以找到官方文档here