Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #78257
| References | <CACwCsY6rL5gQb2Utp1zrDur=1ecD9BjDgSRBn12DnP9U2yTgMA@mail.gmail.com> <CAAhaj_j0So_7HEu1Xsm12MBck_3RCMpmn2P7AwxtaBt2aNy8aA@mail.gmail.com> |
|---|---|
| Date | 2014-09-23 18:20 -0400 |
| Subject | Re: Best way to deal with different data types in a list comprehension |
| From | Larry Martell <larry.martell@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.14293.1411510813.18130.python-list@python.org> (permalink) |
On Tue, Sep 23, 2014 at 6:05 PM, Rock Neurotiko
<miguelglafuente@gmail.com> wrote:
> 2014-09-24 0:01 GMT+02:00 Larry Martell <larry.martell@gmail.com>:
>>
>> I have some code that I inherited:
>>
>> ' '.join([self.get_abbrev()] +
>> [str(f['value')
>> for f in self.filters
>> if f.has_key('value')]).strip()
>>
>>
>> This broke today when it encountered some non-ascii data.
>>
>> I changed the str(f['value']) line to f['value'].encode('utf-8'),
>> which works fine, except when f['value'] is not a string (it could be
>> anything).
>>
>> Without rewriting this without the list comprehension, how can I write
>> this to deal with both strings and non-strings?
> Maybe there are a different way, but you can do this:
>
> ' '.join([self.get_abbrev()] +
> [str(f['value').encode('utf-8') if type(f['value']) is str else
> str(f['value']
> for f in self.filters
> if f.has_key('value')]).strip()
Thanks for the reply, but please don't top post.
This worked for me:
'.join([self.get_abbrev()] +
[f['value'].encode('utf-8') if type(f['value']) is unicode
else str(f['value'])
for f in self.filters
if f.has_key('value')]).strip()
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Best way to deal with different data types in a list comprehension Larry Martell <larry.martell@gmail.com> - 2014-09-23 18:20 -0400
csiph-web