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

Nol*_*way 9 python string formatting

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

例如:

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

请注意,顺序无关紧要.我已经挖了相当数量的字符串.Formatter文档无济于事.我相信你可以写正则表达式,但必须打赌更优雅的方式.

Kev*_*vin 12

看起来您可以使用以下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']
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*rco 5

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

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

编辑:

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

(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))
Run Code Online (Sandbox Code Playgroud)

解释:

(?<=      # 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
Run Code Online (Sandbox Code Playgroud)