escape sequences in list comprehensions

Bengt Richter bokr at oz.net
Sat Nov 13 03:03:57 EST 2004


On Fri, 12 Nov 2004 22:46:17 -0500, Peter Hansen <peter at engcorp.com> wrote:

>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?
>
>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]) + ']'
>
Maybe this is what he wanted (not recommended for general use ;-):

 >>> class FunnyStr(str):
 ...     def __repr__(self): return str(self)
 ...

Plain:
 >>> lst = ['%s\n' % i for i in [1,2,3]]
 >>> lst
 ['1\n', '2\n', '3\n']

Funny:
 >>> lst = [FunnyStr('%s\n' % i) for i in [1,2,3]]
 >>> lst
 [1
 , 2
 , 3
 ]
 >>> print lst
 [1
 , 2
 , 3
 ]

Regards,
Bengt Richter



More information about the Python-list mailing list