【问题标题】:List \n with f-String format使用 f-String 格式列出 \n
【发布时间】:2020-03-08 16:53:47
【问题描述】:

我知道您不能在 f 字符串格式中使用 \n{},但我正在尝试弄清楚如何打印由行分隔的列表。

每个打印数字的宽度应为 10

# Output
#         12
#         28
#         45
#         47
#         52
#         71
#         95
#        122
#        164

我不允许使用任何外部模块,例如 itertools 或 functools 来回答这个问题。

我试过了

num_list = [12, 16, 17, 2, 5, 19, 24, 27, 42]
new_list = num_list.copy()
for n in range(1, len(new_list)):
    new_list[n] += new_list[n-1]

print(f'{*new_list:10f, sep = "\n"}')

【问题讨论】:

  • 你可以循环 iist 吗?
  • 你能给我们看一个示例列表吗?
  • 是的,我们可以循环并使用示例列表编辑列表!
  • print('\n'.join([f'{x:10f}' for x in new_list])) 使用 \n 本身没有限制,但是您将 print 的关键字参数与 f-string 语法混淆了。

标签: python list jupyter-notebook format f-string


【解决方案1】:

谢谢@chepner!!这有效

print('\n'.join([f'{x:10}' for x in new_list]))

【讨论】:

    【解决方案2】:

    试试这个,它会在每个循环中打印一行,并使用 .rjust() 添加 10 个前导空格。

    for n in range(1, len(new_list)):
        new_list[n] += new_list[n-1]
    
    for num in new_list:
        print(f"{num}".rjust(10))
    

    【讨论】:

    • 它工作了,但现在它没有打印第一个数字 (12) 输出是 28 45 47 52 71 95 122 164
    【解决方案3】:

    如果您想按照您的意图坚持使用 f 字符串,只需在进行计算时将其打印出来。这也避免了对列表的额外迭代。

    num_list = [12, 16, 17, 2, 5, 19, 24, 27, 42]
    new_list = num_list.copy()
    
    print(f'{new_list[0]:10}') # This gets you the first value
    
    for n in range(1, len(new_list)):
        new_list[n] += new_list[n-1]
        print(f'{new_list[n]:10}') # This prints as you go
    

    【讨论】:

      【解决方案4】:

      你可以使用str.join:

      print('\n'.join(f'{n}'.rjust(10) for n in  new_list))
      

      或使用内置函数 print 和解压缩的生成器表达式并将分隔符设置为 \n

      print(*(f'{n}'.rjust(10) for n in  new_list), sep='\n')
      

      输出:

          12
          28
          45
          47
          52
          71
          95
         122
         164
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 2022-07-26
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 2022-07-12
        • 2023-02-16
        • 2015-08-13
        相关资源
        最近更新 更多