• Python string formatting
    Code Mastery,  Featured

    String formatting like a pro

    Just about every Python programmer has used the ‘%’ operator for string formatting. But another formatting method is available using the [crayon-5ba869adec62d556787613-i/]  method of the string object. This allows for much cleaner and more readable code than the incantations written using ‘%’ operators.

  • Code Mastery

    Dictionary creation using dict comprehensions

    In a previous Pythonic post we saw list comprehensions, an efficient Pythonic way to create lists.  I hope you got hooked and started using list comprehensions where your code could benefit from them. Similar to list comprehensions, Python has a similar feature that’s applicable to dictionaries. The fancy name? Yes, dictionary comprehensions or dict comprehenions. Without much babbling and tralala, here are dict comprehensions: [crayon-5ba869adec913832695687/] As you can see the basic construct for a dict comprehension is identical to a list comprehension. But instead of wrapping our construct in square brackets we surround it with curly braces. The value returned by our expression inside the dict comprehension should also return…

  • Code Mastery

    Enumerate your iterables!

    Whenever you write code similar to the following: [crayon-5ba869adeca14727744087/] you should consider making your code a bit more Python by using the builtin [crayon-5ba869adeca17011865674-i/]  function: [crayon-5ba869adeca19119863308/] The [crayon-5ba869adeca1a270263945-i/]  function takes an iterable and an optional parameter [crayon-5ba869adeca1b720928383-i/]  (defaulting to 0). The return value is a tuple containing the index of the element and the element itself. And remember, by taking an iterable the enumerate function will also work on builtin types such as dictionaries or your own objects that implement the iterable methods. More information about the [crayon-5ba869adeca1c294780636-i/]  function can be found in the Python documentation.

  • Code Mastery

    Build your lists using list comprehensions

    A common way to build lists in a program that we see is this construct [crayon-5ba869adecb6e124744260/] The basic construct here is that by looping over something (an iterable or a condition) we add items to our list. I’m sure you’ve been there and have already used this construct in some of your code. There is of course a more Pythonic way to do this, otherwise I wouldn’t have made a post about it. Let’s meet list comprehensions. At first they will seem complex and difficult to read and sometimes I write one or see one that still is! But they are actually very neat and easy to use.