简体   繁体   English

如何在 Python 格式字符串迷你语言中给出多个参数(宽度、叹息、分组)?

[英]How do I give multiple arguments(width, sigh, grouping) in Python format string mini-language?

I read format string mini-language from Python doc and tried to do this:我从 Python 文档中读取格式字符串迷你语言并尝试这样做:

a = 20000 # I want "+20,000.00     " for the result 

print(f"a:+,.2f") # >> +20,000.00
print(f"{a:<20+,.2f}") # >> ValueError: Invalid format specifier

print(f"{a:<20,.2f}") # >> '20,000.00           '
print(f"{a:+<20,.2f}") # >> '20,000.00+++++++++++' # Not what I want

Anything else will give ValueError: Invalid format specifier to me.其他任何事情都会给我ValueError: Invalid format specifier

Why is it not possible to use <20 argument with + argument?为什么不能将<20参数与+参数一起使用?

Actually I found this nested form works but it is suboptimal.实际上,我发现这种嵌套形式有效,但不是最理想的。 Is there any other way?还有其他方法吗?

print(f"{f'{a:+,.2f}':<20}") # >> '+20,000.00          ' # It works but nested form sucks. 

Asksed the same question on r/learnpython and got the answer.r/learnpython上问了同样的问题并得到了答案。


efmccurdy有效的

15 minutes ago 15 分钟前

The sign goes before the width:标志在宽度之前:

https://python-reference.readthedocs.io/en/latest/docs/functions/format.html https://python-reference.readthedocs.io/en/latest/docs/functions/format.html

>>> f"{a:<+20,.2f}"
'+20,000.00          '
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在Python格式的迷你语言的所有例子中都有&#39;:&#39;? - Why Is There a ':' In All Examples of Python's format's mini-language? 使用 Python 的 Format Specification Mini-Language 对齐浮点数 - Using Python's Format Specification Mini-Language to align floats 使用format()迷你语言将Floats与Python 2.7中的小数点对齐 - Aligning Floats to decimal points in Python 2.7 using the format() mini-language 使用 Python 的格式规范迷你语言指定或自动确定列宽 - Using Python's Format Specification Mini-Language to specify or automatically determine column widths Python迷你语言格式规范,可从浮点数中删除小数点 - Python mini-language format specification to remove decimal point from float 使用Python3字符串格式化迷你语言打印带有punction的大整数 - Print a big integer with punctions with Python3 string formatting mini-language 提供多个参数以在python中格式化的选项 - option to give multiple arguments to format in python 如何忽略在python中接受多个参数的函数中的字符串? - How do I ignore a string in a function that accepts multiple arguments in python? 如何在python中使用字符串格式排列多个参数 - How do I arrange multiple arguments with string formatting in python 如何使用格式规范迷你语言正确对齐和填充编号与最大宽度 - How to right align and pad number with max width using format specification mini language
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM