[英]Guidance with f-string formatting documentation
I'm currently playing around with f-strings more and trying to figure out how to do things like我目前正在更多地使用 f-strings 并试图弄清楚如何做这样的事情
# Depth and decimal format
f"string text {var: #.#f}"
# Alignment format
f"string text {var: < #}"
I know that is how you would do a depth, decimal, and alignment format for a variable, but how would one format the string text and variable together?我知道这就是您对变量进行深度、小数和对齐格式的方式,但是如何将字符串文本和变量一起格式化? Such as如
f"num = {dartsThrown: < 10d}"
print((f"num ={dartsThrown: < 10d} Calculated PI = {computePI(dartsThrown):.6f} "
f"Difference = {differencePI:+0.6f}"))
how do you combine f-string formatting to both 'num = ' and {var}你如何将 f 字符串格式结合到 'num = ' 和 {var}
Would I have to store it into a variable itself?我是否必须将其存储到变量中?
numVariable = 'num = ' + dartsThrown
f"{numVariable: < ##d}"
or is there another way to do it?或者有另一种方法吗?
You can put the alignment specification before the width specification, per the documentation of the Format Specification Mini-Language :根据Format Specification Mini-Language的文档,您可以将对齐规范放在宽度规范之前:
>>> var=1.23
>>> f'{var:<8.1f}'
'1.2 '
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.