繁体   English   中英

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

[英]How to check if string has format arguments in Python?

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

例如:

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

请注意,顺序无关紧要。 我已经挖了相当数量的字符串.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()过滤后两个,并分别与空字符串进行比较。

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

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

编辑:

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

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

说明:

 (?<= # 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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM