首页 > 解决方案 > 使用 f 字符串生成打印

问题描述

假设我有:

text = ['Apple', 'Banana']

我想使用 f-string 来打印项目。我的预期输出是:

items are:
Apple
Banana

到目前为止,我尝试过:

print(f'items are: {i for i in text}')

这打印:items are: <generator object <genexpr> at 0x0BBCB660>

我怎样才能达到预期的输出?请注意,我也需要反斜杠。

标签: pythonf-string

解决方案


text = ['Apple', 'Banana']
nl = '\n'
print(f'items are: {nl}{nl.join(text)}')

输出:

items are: 
Apple
Banana

我没有在 f-string 中使用 \n 的原因是因为你不能在 fstrings 中使用反斜杠


推荐阅读