如何在python 3中使用花括号{}打印列表项?

时间:2020-07-01 15:06:51

标签: python python-3.x

我的代码如下,我想将x的值打印在y中花括号的位置。

x = ['abc']
y= "{0} college"

4 个答案:

答案 0 :(得分:1)

您可以使用f字符串(带格式的字符串)。

f'{x[0]} college' # To print the first index

在python3.8中,您可以在f字符串中使用=说明符,这在打印调试语句时非常方便

f'{x[0]=} college' # prints x[0]='abc' college

official python page

中的一个更好的例子
>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

答案 1 :(得分:0)

x = ['abc']
y= f"{x} college"

请注意,在您给出的示例中,输出为:

['abc'] college

因为x是一个列表。如果只想显示“ abc”,则可以执行以下操作:

x = 'abc'
y = f"{x} college"

正在发生的事情::自Python 3.6起,您可以使用此f字符串语法设置字符串格式。您可以在字符串的前面加上字母f,然后在大括号{}的字符串中包含要打印在字符串中的所有变量。

答案 2 :(得分:0)

您可以使用如下所示的f字符串进行此操作。您可以看到此here的PEP。您需要确保使用的是python 3.6及更高版本

x = ['abc']
y= f'{x} college'

答案 3 :(得分:0)

尝试:

x = ['abc']
y= "{0} college"

print(y.format(*x))

输出:

abc college