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.
"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.
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.
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.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With