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 mo开发者_JS百科re graceful way of achieving the same result?
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))
"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.
Well, you can leave out the str()
call, but that's about it. How come is calling functions "a hack"?
精彩评论