How to check if a string has format arguments in Python?

I format strings using named arguments with .format(). How to get a list of arguments?

For instance:

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

Note that the order does not matter. I dug a fair amount into the string.Formatter documentation to no avail. I'm sure you could write regex to do this, but you need to do a more elegant way.

+4
source share
2 answers

It looks like you can get the field names using the method 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() .

+5

Regex .

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

Edit:

'{{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 possible to match...
 \}       #  a }
 (?!\})   #  (only if there is not another } that follows)
)         # End of lookahead
+1

Source: https://habr.com/ru/post/1685483/


All Articles