python 如何清除这些打印语句?

kzipqqlq  于 2022-11-28  发布在  Python
关注(0)|答案(3)|浏览(213)

所以,我在玩.csv文件,学习如何阅读和呈现信息。我把结果打印到终端,但随着我打印的内容越来越多,我有一堵墙的打印语句,只是越来越长。有什么办法来清理这一点吗?还有,请忽略我的粗俗数据。我生成的csv在凌晨3点左右。

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
m4pnthwp

m4pnthwp1#

avg = round(get_avg(people))
plugs = people[owner]['plugs']
print(
    f'\n{people[owner]["first_name"]} {people[owner]["first_name"]} '
    f'owns the most buttplugs with a total of {plugs} buttplugs!\n'
    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!
vuktfyat

vuktfyat2#

你可以把它们合并成两个print语句,每个逗号会照顾到中间的一个空格,你必须把数字转换成字符串

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字符串语句

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}!")
q9yhzks0

q9yhzks03#

f-strings是您正在寻找的。它们允许您以一种非常可读的方式轻松地格式化代码。例如:

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

相关问题