I came accross this snippet:
li = ['a', 'b', 'c']
print "\n".join(li)
The author says:
This is also a useful debugging trick when you’re working with lists.
What is the trick here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Printing a list like that is useless for debugging:
(1) If any of the list items are not strings, you will get an exception.
(2) Your stdout may not be able to display the strings, resulting in an exception or just gibberish.
(3) You won’t see the difference between (for example) tabs (
\t) and multiple spaces.Much better:
Python 2.x :
print repr(li)Python 3.x :
print(ascii(li))Update Here’s what can happen with
print(li')on Python 3.x (it’s problem 2 above):Note that
print li“works” on Python 2.x only becauserepr()is called implicitly. In general one should just doprint repr(thing). Note also thatprint(li)can fail on Python 3.x because it implicitly callsrepr(), notascii()Update 2 If you want to find all non-strings in a list, do it explicitly, don’t rely on “tricks”: