[英]Python: Format string with float, right alignment
I want to align a combination of str and float to the right side.我想将 str 和 float 的组合对齐到右侧。 In my example, "Tax = $" is a string and tax is a float.
在我的示例中,“Tax = $”是一个字符串,而 tax 是一个浮点数。 I have two ways to accomplish this.
我有两种方法来实现这一点。
print(("Tax = $%.2f" % tax).rjust(70))
print("%66s%.2f" % ("Tax = $",tax))
The output is the following:输出如下:
Tax = $0.42
Both of them are working.他们俩都在工作。 But I don't think they are good enough.
但我认为他们还不够好。 The codes are kind of burdensome.
这些代码有点繁重。 At the beginning, I wrote something like
一开始,我写了类似的东西
print("Tax = $%.2f" % tax)
I tried to put a right align flag in this line, but I don't know where should I put it in.我试图在这一行中放置一个右对齐标志,但我不知道我应该把它放在哪里。
Is there a neat way to do this?有没有一种巧妙的方法来做到这一点?
Thank you,谢谢,
Now with f-strings available in python 3.6 and newer, here is another way to look at it:现在有了 python 3.6 和更新版本中的 f-strings,这里是另一种看待它的方式:
print(f"{(f'Tax = ${tax:.2f}'):>70}")
Using temporary variables:使用临时变量:
rightSideStuff = f'Tax = ${tax:.2f}'
print(f"{rightSideStuff:>70}")
The resource I used for finding how to align right: https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e我用于查找如何正确对齐的资源: https : //medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.