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

时间:2017-09-11 17:57:17

标签: python string formatting

我使用.format()的命名参数格式化字符串。我怎样才能获得参数列表?

例如:

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

请注意,顺序无关紧要。我在string.Formatter文档中挖了相当数量但无济于事。我相信你可以编写正则表达式,但必须以更优雅的方式下注。

2 个答案:

答案 0 :(得分:8)

看起来您可以使用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()过滤掉后两者,并分别与空字符串进行比较。

答案 1 :(得分:2)

正则表达式可以解决您的问题。

>>> import re 
>>> re.findall(r'{(.*?)}', 'I live in {city}, {state}, {country}.')
['city', 'state', 'country']

修改

为避免匹配转义占位符(如'{{city}}'),您应将模式更改为:

(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))

Explanation:

(?<=      # Assert that the following can be matched before the current position
 (?<!\{)  #  (only if the preceding character isn't a {)
\{        #  a {
)         # End of lookbehind
[^{}]*    # Match any number of characters except braces
(?=       # Assert that it's possible to match...
 \}       #  a }
 (?!\})   #  (only if there is not another } that follows)
)         # End of lookahead