Python3 – 在 f 字符串中用 \n 分隔的打印列表

Python3 – print list separated with \n inside an f-string

我想在 python3.

的 f 字符串中打印一条消息,其中包含一个由 \n 分隔的列表
my_list = ["Item1", "Item2", "Item3"]
print(f"Your list contains the following items:\n\n{my_list}")

期望的输出:

# Your list contains the following items:
#    Item1
#    Item2
#    Item3

使用 join()(请参阅加入 here 的文档)

joined_list = '\n'.join(my_list)
print(f"Your list contains the following items:\n{joined_list}")

我知道您特别要求使用 f 字符串,但实际上我只想使用旧样式:

print("Your list contains the following items:\n%s" %'\n'.join(my_list))

一种可能的解决方案,chr(10) 计算为换行符:

my_list = ["Item1", "Item2", "Item3"]
print(f"Your list contains the following items:\n{chr(10).join(my_list)}")

打印:

Your list contains the following items:
Item1
Item2
Item3

您可以使用辅助函数:

>>> my_list = ["Item1", "Item2", "Item3"]
>>> def cr(li): return '\n'.join(li)
... 
>>> print(f"Your list contains the following items:\n{cr(my_list)}")
Your list contains the following items:
Item1
Item2
Item3

要获得准确的示例:

>>> def cr(li): return '\n\t'.join(li)
... 
>>> print(f"Your list contains the following items:\n\t{cr(my_list)}")
Your list contains the following items:
    Item1
    Item2
    Item3