python - printf style "%0*d" % (m, n) -- 如果使用映射键,等效形式是什么 ("%???d" % { "width": m, "num": n })
问题描述
我需要格式化涉及相当多变量的长行,所以我使用映射键样式格式。(我个人不喜欢str.format()
。:)
我尝试了很多,但未能找出正确的语法应该是什么。
使用元组参数它可以正常工作:
>>> width = 6
>>> num = 123
>>>
>>> '%0*d' % (width, num)
'000123'
我无法弄清楚如何使用 dict 参数来做到这一点:
>>> '%(width)0*d' % dict(width=width, num=num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>>
>>> '%(width)(num)0*d' % dict(width=width, num=num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unsupported format character '(' (0x28) at index 8
>>>
>>> '%(width)0*(num)d' % dict(width=width, num=num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
现在我正在使用一些解决方法。只是好奇这是可能的还是根本不支持。
解决方案
事实证明它不受支持。在The Python Library Reference中找到了这个(见最后一句话):
当正确的参数是字典(或其他映射类型)时,字符串中的格式必须在字符之后立即插入到该字典中的带括号的映射键
'%'
。映射键从映射中选择要格式化的值。例如:>>> print('%(language)s has %(number)03d quote types.' % ... {'language': "Python", "number": 2}) Python has 002 quote types.
在这种情况下
*
,格式中不能出现说明符(因为它们需要顺序参数列表)。
推荐阅读
- python - 由于 Cloudflare,从今天开始无法使用 BeautifulSoup 解析 coin gecko 页面
- hadoop - 如何调整 HDFS 和 Yarn 的 SecurityAuth 审计日志?
- spring-boot - Artemis v2.17.0 和 Spring Boot 中的通配符路由问题
- php - 如何使用 hook_user_login 创建自定义模块以覆盖 drupal 中的核心功能?
- python - 如何将回调重定向到不同的子域
- asp.net-core - 检查用户是否已在网站或应用程序启动时登录 okta。这样我们就不需要再次登录
- postgresql - 如何为 postgresql jsonb 字段(数组数据)和文本字段创建索引
- c# - 使用 Control.BeginInvoke() 调用异步方法时如何防止警告 VSTHRD101?
- mysql - Mysql中select和group by的执行顺序
- azure - 使用 Azure Databricks 从 ADLS 访问数据