custom formatter in python 3

from string import Formatter
class ExtendedFormatter(Formatter):
"""
>>>myformatter = ExtendedFormatter()
>>>output = myformatter.format("normal:{test}, upcase:{test!u},
lowcase:{test!l}", test="DiDaDoDu")
>>>print(output)
normal:DiDaDoDu, upcase:DIDADODU, lowcase:didadodu
All default formatting still supported
>>>myformatter.format("UKP {:.1f}", 444.44543)
>>>print(output)
UKP 444.4
"""

def convert_field(self, value, conversion):
""" Extend conversion symbol
Following additional symbol has been added
* l: convert to string and lowercase
* u: convert to string and uppercase
"""
RECOGNIZED_FORMATTERS = {
'u': lambda value: str(value).upper(),
'l': lambda value: str(value).lower(),
}
try:
return RECOGNIZED_FORMATTERS[conversion](value)
except KeyError:
# Do the default conversion
return super(ExtendedFormatter,self).convert_field(
value, conversion)

A few notes on the Python

def upper(value):
return str(value).upper()

--

--

developer,developer,developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store