Back to main.

Calmcode Shorts

Sometimes you want to be able to represent a string nicely. Take the number 7. You can just write 7, but sometimes it might look nicer to write seven instead.

For stuff like this, you might enjoy having a look at the humanize project. It's an open-source tool that allows you to turn Python objects into more human readable strings. It has a ton of features, but here's a nice subset to help understand what it can do.

import humanize 
import datetime as dt

# 'seven'

# 'zero'

# '12.3 thousand'

humanize.intword(12345, "%.2f")
# '12.35 thousand'

# '1st'

# '2nd'

# '5th'

humanize.metric(1800, "V")
# 1.80 kV

# 'today'

humanize.naturaltime( - dt.timedelta(days=1))
# 'yesterday'

humanize.naturaltime( - dt.timedelta(seconds=7))
# '7 seconds ago'

One of the great features of the library is that it doesn't do English, it does a bunch of languages! Here's how you can set the local to Dutch:

humanize.naturaltime( - dt.timedelta(seconds=7))
# '7 seconden geleden'

At the time of writing it support 31 languages (including Klingon!), so there's a lot to like here. We're only covering some of the functionality here, the project also supports filesizes as well as scientific notiation if that souds useful. Definately check out the documentation is this sounds useful!

Back to main.