【问题标题】:Python3 – print list separated with \n inside an f-string [duplicate]Python3 – 在 f 字符串中用 \n 分隔的打印列表 [重复]
【发布时间】:2020-08-26 07:02:21
【问题描述】:

我想在 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

【问题讨论】:

    标签: python python-3.x f-string


    【解决方案1】:

    一种可能的解决方案,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
    

    【讨论】:

    • 不错!我正在为类似的事情挠头……
    • @Andrej Kesely 这行得通,但是在它通过成为一条线获得的地方,在我看来,它会因为缺乏清晰度而松动。如果你把它放在你的代码中,你会想要记录 chr(10)evaluates 到一个换行符。在这种情况下,你甚至不是一条线。我个人会清楚地保留\n 并将join() 与打印分开,但这可能只是我。作为调试打印可能很有用,我猜你不会留在代码中。
    • @GlennMackintosh 是的,它不是 生产 级代码。我自己,我会选择单独的'\n'.join(...) - 它更清楚。
    【解决方案2】:

    使用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))
    

    【讨论】:

    • f 字符串不能表达式部分不能包含反斜杠。这是语法错误。
    • @dawg 刚刚运行它并注意到了这一点。编辑更正..@Andrej Kesely 看起来 yuo 不能在 f 字符串中完成所有操作,并且由于您想要分隔符的 \n 必须将其分解。
    【解决方案3】:

    你可以使用辅助函数:

    >>> 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多