views:

84

answers:

3

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?

+8  A: 

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))  
Mark Byers
+1  A: 

Well, you can leave out the str() call, but that's about it. How come is calling functions "a hack"?

Matti Virkkunen
it just looks ugly, and i have often found that python has more streamlined ways of doing things than I think of
mvid
+2  A: 

"Length: %d" % len(self.listOfThings) should work great.

The point of string formatting is to make your data into a string, so calling str is not what you want: provide the data itself, in this case an int. An int can be formatted many ways, the most common being %d, which provides a decimal representation of it (the way we're used to looking at numbers). For arbitrary stuff you can use %s, which calls str on the object being represented; calling str yourself should never be necessary.

I would also consider "Length: %d" % (len(self.listOfThings),)—some people habitually use tuples as the argument to str.__mod__ because the way it works is sort of funny and they want to provide something more consistent.

If I was using print in particular, I might just use print "Length:", len(self.listOfThings). I seldom actually use print, though.

Mike Graham