我正在使用带有 .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()
并分别与空字符串进行比较来过滤掉后两者。
关于python - 如何在 Python 中检查字符串是否具有格式参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161710/