Custom format a la datetime

Peter Otten __peter__ at web.de
Sat Apr 18 16:29:03 EDT 2015


santiago.basulto at gmail.com wrote:

> Hello everybody. I'm writing a CLI program to do some search. It's an
> internal tool. I'd like to provide the option to my user to format the
> results as he/she'd like. Something similar to strftime on the datetime
> module.
> 
> Example:
> 
>     from datetime import datetime
>     d = datetime.utcnow()
>     d.strftime("%Y-%m-%d")  # '2015-04-18'
>     d.strftime("%y-%m-%d")  # '15-04-18'
>     d.strftime("Today it's the %dth day in the %mth month of %Y") # 'Today
>     it's the 18th day in the 04th month of 2015' # Don't pay attention to
>     ordinals, just simple example.
> 
> Now, an example of with my application. Suppose my app search cars:
> 
>     python search_cars.py -F "Brand %B, model %m, year %Y"  # Brand Ford,
>     model Focus, year 1996
>     python search_cars.py -F "%B - %m (%y)"  # Ford - Focus (96)
> 
> I'd provide my user with a table like:
> 
> %B = Brand
> %m = Model
> %Y = Year format YYYY
> %y = Year format YY
> %s = Seller name
> ... etc...
> 
> Thanks a lot for your help!

Make a dict to map the format to a function that extracts the value you are 
interested in from a record you found with your search. Then replace the 
format in the template with the value returned from that function.

>>> import re
>>> record = dict(brand="Ford", model="Focus", year=1996)
>>> format = {"B": lambda r: r["brand"],
... "m": lambda r: r["model"],
... "Y": lambda r: str(r["year"]),
... "y": lambda r: "{:02}".format(r["year"] % 100),
... }
>>> template = "Brand %B, model %m, year %Y"
>>> re.compile("%(.)").sub(lambda m: format[m.group(1)](record), template)
'Brand Ford, model Focus, year 1996'
>>> template = "%B - %m (%y)"
>>> re.compile("%(.)").sub(lambda m: format[m.group(1)](record), template)
'Ford - Focus (96)'

To allow literal % signs add

format = {
    ...
    "%": lambda r: "%"
}

to the lookup dict.

For alternative approaches have a look at string.Template, str.format() etc.






More information about the Python-list mailing list