string methods (warning, newbie)

Steven Bethard steven.bethard at gmail.com
Sun Feb 27 20:12:17 EST 2005


Nick Coghlan wrote:
> Jimmy Retzlaff wrote:
> 
>> The approach you are considering may be easier than you think:
>>
>>>>> filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride')
>>
>> 'TheBeatleshelpTickettoride'
> 
> Hmm, I think this is a case where filter is significantly clearer than 
> the equivalent list comprehension:
> 
> Py> "".join([c for c in 'The Beatles - help - 03 - Ticket to ride' if 
> c.isalpha(
> )])
> 'TheBeatleshelpTickettoride'

On the other hand, filter doesn't do the same thing:

py> s = u'The Beatles - help - 03 - Ticket to ride'
py> filter(str.isalpha, s)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: descriptor 'isalpha' requires a 'str' object but received a 
'unicode'
py> ''.join(c for c in s if c.isalpha())
u'TheBeatleshelpTickettoride'

Ideally, you could use something like basestring.isalpha and have it 
work for both str and unicode, but no such luck. =)

STeVe



More information about the Python-list mailing list