escape sequences in list comprehensions

Kent Johnson kent3737 at yahoo.com
Fri Nov 12 08:46:46 EST 2004


kartik wrote:
> 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?

This is correct; what were you expecting?

When you print a list, it prints the repr() of the list elements. In the 
case of strings, it shows you the escaped form of the string. Maybe this 
is what you want:
 >>> a=['%s\n' %i for i in [1,2,3]]
 >>> a
['1\n', '2\n', '3\n']
 >>> for x in a:
...   print x
...
1

2

3

 >>>

Note the extra lines when the strings are actually printed.

Kent

> 
> Thank you.



More information about the Python-list mailing list