【问题标题】:How can I clean up these print statements?我怎样才能清理这些打印报表?
【发布时间】:2022-11-27 05:36:46
【问题描述】:

所以,我正在玩 .csv 文件,学习如何阅读和呈现信息。我正在将结果打印到终端,但是当我打印更多内容时,我有一堵打印报表墙,而且越来越长。有什么办法可以清理这个吗?另外,请无视我的低俗数据。我在凌晨 3 点左右生成了那个 csv。

print("")
print(people[owner]["first_name"], end = "")
print(" ", end="")
print(people[owner]["last_name"], end="")
print(" owns the most buttplugs with a total of ",end="")
print(people[owner]["plugs"], end="")
print(" buttplugs!")
print("That's ",end="")
print(people[owner]["plugs"] - round(get_avg(people)),end="")
print(" more buttplugs than the average of ",end="")
print(round(get_avg(people)),end="")
print("!")
print("")
# Result: Sonnnie Mallabar owns the most buttplugs with a total of 9999 buttplugs!
# That's 4929 more buttplugs than the average of 5070

【问题讨论】:

  • 你为什么说Also, please ignore my vulgar data.而不是不发布低俗数据?

标签: python printing readability


【解决方案1】:
avg = round(get_avg(people))
plugs = people[owner]['plugs']
print(
    f'
{people[owner]["first_name"]} {people[owner]["first_name"]} '
    f'owns the most buttplugs with a total of {plugs} buttplugs!
'
    f"That's {plugs - avg} more buttplugs than the average of {avg}!"
)

印刷

Sonnnie Sonnnie owns the most buttplugs with a total of 9999 buttplugs!
That's 4929 more buttplugs than the average of 5070!

【讨论】:

    【解决方案2】:

    您可以将它们组合成 2 个打印语句。每个逗号都会处理中间的空格,您必须将数字转换为字符串

    print(people[owner]["first_name"], people[owner]["last_name"], "owns the most buttplugs with a total of", str(people[owner]["plugs"]), "buttplugs!")
    print("That's", str(people[owner]["plugs"] - round(get_avg(people))), "more buttplugs than the average of", str(round(get_avg(people))), "!")
    

    或 2 个使用 f-string 的语句

    first_name = people[owner]["first_name"]
    last_name = people[owner]["last_name"]
    total = people[owner]["plugs"]
    diff = people[owner]["plugs"] - round(get_avg(people))
    avg = round(get_avg(people))
    print(f"{first_name} {last_name} owns the most buttplugs with a total of {total} buttplugs!")
    print(f"That's {diff} more buttplugs than the average of {avg}!")
    

    【讨论】:

      【解决方案3】:

      f-strings 是你要找的。它们允许您以非常易读的方式轻松地格式化您的代码。例子:

      print(f'{people[owner]["first_name"]} won the prince...')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2021-04-18
        • 2016-08-28
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        相关资源
        最近更新 更多