escape sequences in list comprehensions
peter at engcorp.com
Sat Nov 13 04:46:17 CET 2004
> Escape sequences don't seem to work in strings within list comprehensions:
>>>>print ['%s\n' %i for i in [1,2,3]]
> ['1\n', '2\n', '3\n']
> What am I missing?
Others have answered, but not explained. When you print
a list (in other words, when you display the results of
calling str() on a list), the list chooses how to display
itself. It chooses to display the brackets at the start
and end, the commas separating the items, and the results
of calling repr() on each individual item. That means
that strings are shown with quotation marks (which are not
part of the string normally) and with special characters
represented as escape sequences.
The following appears to be what you believed you wanted,
though it's not really what you wanted <wink>:
lst = ['%s\n' % i for i in [1,2,3]]
print '[' + ', '.join([str(x) for x in lst]) + ']'
More information about the Python-list