我有一个带有格式化输出的控制台程序。为了始终获得相同的打印输出长度,我有一个相当复杂的格式化打印输出。
print(f"\n{WHITE_BG}{64*'-'}")
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-{(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")
这会在Windows cmd中导致以下输出
出于可读性目的,我尝试在多行上进行打印,因此我在stackoverflow上发现了以三引号开头的想法。但是,当我在中间剪切此print(f“ ...”)语句时,我弄乱了格式。
示例:
print(f"\n{WHITE_BG}{64*'-'}") #als String einspeisen?!
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-
{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-
{(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")
导致...
任何人都可以向我指出正确的方向,如何以显示的方式格式化我的输出,但又不用这么长的行长。
谢谢大家!
答案 0 :(得分:2)
用三引号引起来的字符串保留换行符,因此,它们的确不是您想要的。现在,当它找到两个相邻的字符串时,Python解析器会自动将它们串联为一个字符串,即:
s = "foo" "bar"
等同于
s = "foobar"
如果您将字符串放在括号内,这将起作用:
s = ("foo" "bar")
在这种情况下,您也可以将每个字符串放在自己的行上:
s = (
"foo"
"bar"
)
这也适用于“ fstrings”,因此您想要的是这样的:
print((
f"{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN} "
f"{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-"
f"{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}"
f"{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-"
f"len(players[1].name))*'~'}\n"
))
话虽这么说,我宁愿使用中间变量,而不是尝试在fstring中填充这样的复杂表达式。