python - 如何在 Python 中检查字符串是否具有格式参数?

我正在使用带有 .format() 的命名参数来格式化字符串。如何获取参数列表?

例如:

>>> my_string = 'I live in {city}, {state}, {country}.'
>>> get_format_args(my_string)
# ['city', 'state', 'country']

请注意,顺序无关紧要。我已经在 string.Formatter 中挖掘了相当多的数据。文档无济于事。我相信你可以编写正则表达式来做到这一点,但是必须打赌一个更优雅的方式。

最佳答案

看起来您可以使用 Formatter.parse 方法获取字段名称:

>>> import string
>>> my_string = 'I live in {city}, {state}, {country}.'
>>> [tup[1] for tup in string.Formatter().parse(my_string) if tup[1] is not None]
['city', 'state', 'country']

这也将返回非命名参数。示例:"{foo}{1}{}" 将返回 ['foo', '1', '']。但如果需要,您可以通过使用 str.isdigit() 并分别与空字符串进行比较来过滤掉后两者。

https://stackoverflow.com/questions/46161710/

相关文章:

c# - Visual Studio/ReSharper 代码格式化 - C#

c# - 如何格式化带有千位分隔符和小数点分隔符的 Windows 窗体文本框以进行数字输入

powershell - 将整数 x.xxxxx 格式化为 xx.xxx

excel - 条件格式 : making cells colorful

python - 在 Python Pandas DataFrame 或 Jupyter Noteb

c# - 解释令人困惑的条件字符串格式

python - 是否可以使用 weasyprint 对页脚进行精美的格式化?

io - 使用英特尔 Fortran 编译器避免列表导向输出中的换行符

mysql - MySQL中的字符串格式化

python - Python中的十进制对齐格式