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
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 __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.)
"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.
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.
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
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