Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default kwarg values for Python's str.format() method

I'm looking to try and keep pluralisation of existing strings as simple as possible, and was wondering if it was possible to get str.format() to interpret a default value when looking for kwargs. Here's an example:

string = "{number_of_sheep} sheep {has} run away"
dict_compiled_somewhere_else = {'number_of_sheep' : 4, 'has' : 'have'}

string.format(**dict_compiled_somewhere_else)
# gives "4 sheep have run away"

other_dict = {'number_of_sheep' : 1}
string.format(**other_dict)
# gives a key error: u'has'
# What I'd like is for format to somehow default to the key, or perhaps have some way of defining the 'default' value for the 'has' key 
# I'd have liked: "1 sheep has run away"

Cheers

like image 783
Patrick Avatar asked May 01 '14 12:05

Patrick


People also ask

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 __ format __ do in Python?

The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)

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.

Which formatting methods in Python 3 allows multiple substitutions and value formatting?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.


Video Answer


1 Answers

As PEP 3101, string.format(**other_dict) is not available.

If the index or keyword refers to an item that does not exist, then an IndexError/KeyError should be raised.

A hint for solving the problem is in Customizing Formatters, PEP 3101. That uses string.Formatter.

I improve the example in PEP 3101:

from string import Formatter

class UnseenFormatter(Formatter):
    def get_value(self, key, args, kwds):
        if isinstance(key, str):
            try:
                return kwds[key]
            except KeyError:
                return key
        else:
            return Formatter.get_value(key, args, kwds)

string = "{number_of_sheep} sheep {has} run away"
other_dict = {'number_of_sheep' : 1}

fmt = UnseenFormatter()
print fmt.format(string, **other_dict)

The output is

1 sheep has run away
like image 164
emeth Avatar answered Sep 17 '22 14:09

emeth