【问题标题】:Python 3, difference between print("x:\n{}".format(x)) and print("x:\n",x)?Python 3,print("x:\n{}".format(x)) 和 print("x:\n",x) 之间的区别?
【发布时间】:2018-04-05 03:38:08
【问题描述】:
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 时,点指的是什么? “”里面有什么? 为什么我们需要 {}?

谢谢

【问题讨论】:

  • "x:\n{}".format(x) 返回一个字符串,然后打印出来,而第二个示例将两个参数传递给print function,一个是字符串,一个是列表

标签: python-3.x printing


【解决方案1】:

花括号将包含 “替换” 字段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

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 2012-10-06
    • 2013-06-19
    • 2018-10-22
    • 1970-01-01
    • 2013-06-14
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多