Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the list of names used in a formatting string?

Given a formatting string:

x = "hello %(foo)s  there %(bar)s"

Is there a way to get the names of the formatting variables? (Without directly parsing them myself).

Using a Regex wouldn't be too tough but I was wondering if there was a more direct way to get these.

like image 742
qhfgva Avatar asked Dec 31 '14 17:12

qhfgva


People also ask

What does {: 3f mean in Python?

"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.

What is str format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What does {: D do in Python?

The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.

How do I format a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

Use a dict subclass with overridden __missing__ method and from there you can collect all the missing format variables:

class StringFormatVarsCollector(dict):
    def __init__(self, *args, **kwargs):
        self.format_vars = []

    def __missing__(self, k):
        self.format_vars.append(k)
...         
def get_format_vars(s):
    d = StringFormatVarsCollector()     
    s % d                    
    return d.format_vars
... 
>>> get_format_vars("hello %(foo)s  there %(bar)s")
['foo', 'bar']
like image 173
Ashwini Chaudhary Avatar answered Oct 19 '22 10:10

Ashwini Chaudhary


If you don't want to parse the string, you can use this little function:

def find_format_vars(string):
    vars= {}
    while True:
        try:
            string%vars
            break
        except KeyError as e:
            vars[e.message]= ''
    return vars.keys()

>>> print find_format_vars("hello %(foo)s there %(bar)s") ['foo', 'bar']

like image 42
Aran-Fey Avatar answered Oct 19 '22 11:10

Aran-Fey