[英]How can I print curly braces with this style formatted text in python
[英]How to get to print an item of a list in using curly braces {} in python 3?
我的代码如下,我想打印 x 的值来代替 y 中的花括号。
x = ['abc']
y= "{0} college"
您可以使用 f 字符串(格式化的字符串文字)。
f'{x[0]} college' # To print the first index
从 python3.8 开始,您可以在 f 字符串中使用=
说明符,这在打印调试语句时非常方便
f'{x[0]=} college' # prints x[0]='abc' college
来自官方 python 页面的更好的例子
>>> print(f'{theta=} {cos(radians(theta))=:.3f}')
theta=30 cos(radians(theta))=0.866
x = ['abc']
y= f"{x} college"
请注意,在您给出的示例中,output 将是:
['abc'] college
因为x
是一个列表。 如果您只想显示“abc”,那么您可以这样做:
x = 'abc'
y = f"{x} college"
发生了什么:从 Python 3.6 开始,您可以使用这种 f-string 语法格式化字符串。 您将字母f
添加到您的字符串中,然后在大括号{}
中包含您想要在字符串中打印的任何变量。
您可以使用如下的 f 字符串来执行此操作。 您可以在此处查看 PEP。 您需要确保您使用的是 python 3.6 及更高版本
x = ['abc']
y= f'{x} college'
尝试:
x = ['abc']
y= "{0} college"
print(y.format(*x))
输出:
abc college
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.