Python niceties

nicety (plural niceties)

  1. A small detail that is nice or polite to have but isn’t necessary.

Make a comma-separated string

>>> x = ['a', 'b', 'c']
>>> ', '.join(x)
'a, b, c'

Isn’t that prettier than some big loop?

If you want to join a list of elements that aren’t strings, you’ll have to add a step:>>> x = [1, 2, 3]
>>> ', '.join(map(str, x))
'1, 2, 3'

I’m using map to convert every element to a string first.

Choose a random element from a sequence

>>> from random import choice
>>> choice(x) # doctest: +SKIP
1

The doctest: +SKIP text is just there because the element returned is randomly chosen, and so I can’t predict what the value will be.

Use keyword parameters in your larger string templates

Well-named keywords make big string templates MUCH easier to deal with:>>> tmpl = """
... Dear %(display_name)s,
...
... Greetings from %(origin_country)s! I have millions of
... %(currency_type)s in my bank account and I can send it all to you if
... you first deposit %(amount)s %(currency_type)s into my account
... first.
...
... Sincerely,
... %(alias)s
... %(origin_country)s
... """

Seeing the key names makes it much easier to remember what gets interpolated. Also, it makes it easier to use the same values more than once.

Usually I pass in a dictionary to the template, but sometimes I do this instead:>>> display_name = 'Matt'
>>> origin_country = 'Nigeria',
>>> currency_type = 'US dollars'
>>> amount = '250.00'
>>> s = tmpl % locals()

11 thoughts on “Python niceties

  1. I'd write the 2nd example using a list comrehension:

    >>> x = [1, 2, 3]
    >>> ', '.join([str(z) for z in x])
    '1,2,3'

    or using a generator comprehension for python 2.4 and up :

    >>> x = [1, 2, 3]
    >>> ', '.join(str(z) for z in x)
    '1,2,3'

    which is is more natural (at least for me 😉

  2. Thanks for the comment!

    Yeah, I use list comprehensions and generator expressions plenty too.
    In this one case, I like map just because it is so much shorter.

    Matt

  3. A variation on the first tip is to make a list from a string.
    For example, if I want days of the week in a list, I can do:

    >>> 'monday tuesday wednesday thursday friday saturday sunday'.split()

    It is much simple than having to type lot of quotes and comas.

  4. Reminds me of Ruby's array literals:
    a = %w( ant bat cat dog )
    After a year of Ruby I still prefer Python.

Comments are closed.