2

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?

3 Answers 3

9

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))  
Sign up to request clarification or add additional context in comments.

Comments

2

"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.

Comments

1

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

1 Comment

it just looks ugly, and i have often found that python has more streamlined ways of doing things than I think of

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.