Search code examples
pythonstringconventions

Python List length as a string


Is there a preferred (not ugly) way of outputting a list length as a string? Currently I am nesting function calls like so:

print "Length: %s" % str(len(self.listOfThings))  

This seems like a hack solution, is there a more graceful way of achieving the same result?


Solution

  • You don't need the call to str:

    print "Length: %s" % len(self.listOfThings)
    

    Note that using % is being deprecated, and you should prefer to use str.format if you are using Python 2.6 or newer:

    print "Length: {0}".format(len(self.listOfThings))