Python间距和%

use*_*356 0 python spacing

我需要输出这个:

视频游戏:8/8(或100.0%)

这是8中标记的代码:

total = points+pointsTwo+pointsThree+pointsFour
Run Code Online (Sandbox Code Playgroud)

我将如何编写此代码以准确输出上面所写的精确间距?

我试过了:

print("Video Games:", total, "/8  (or", total*100/8,"%)")
Run Code Online (Sandbox Code Playgroud)

但是有一个空间; 8/8而不是8/8和另一个空间; 100.0%而不是100.0%

小智 5

您可以使用String格式(对于Python 2或3),如下所示:

out = "Video Games: {total}/8 (or {percent}%)".format(total=total, percent=total*100/8)
print(out)
Run Code Online (Sandbox Code Playgroud)

在Python 3.0中,上面给出:

Video Games: 7/8 (or 87.5%)
Run Code Online (Sandbox Code Playgroud)

或者在Python 2.0中得到以下内容(由于整数除法):

Video Games: 7/8 (or 87%)
Run Code Online (Sandbox Code Playgroud)

编辑:所有归功于Gnibbler:

它可以通过让字符串格式化程序负责计算百分比来以更短,更可控的方式完成:

out = "Video Games: {total}/8 (or {ratio:.2%})".format(total=total, ratio=total/8.0)
print(out)
Run Code Online (Sandbox Code Playgroud)

同时给出(注意小数点和尾随零):

Video Games: 7/8 (or 87.50%)
Run Code Online (Sandbox Code Playgroud)