John Fouhy wrote:
> On 18/09/2007, Andrew Nelsen <[EMAIL PROTECTED]> wrote:
>   
>> I was wondering, recently, the most expedient way to take a string with
>> [EMAIL PROTECTED]&*] and alpha-numeric characters [ie. "[EMAIL 
>> PROTECTED]@*$g@)$&^@&^$F"] and
>> place all of the letters in a string or list. I thought there could be
>> obvious ways:
>>
>> A) Find all the letters, put them in a list, one by one. Something like (I'm
>> not sure yet how I'd do it...):
>>
>> import string
>> list = {}
>> string = "@*&^$&[EMAIL PROTECTED](&@$*(&[EMAIL PROTECTED](*&*(&c^&%&^%"
>> for x in string:
>>     if x <is in string.letters?>
>>         list = list + [x]
>>     
>
> Hi Andrew,
>
> First up, you should not reuse the name 'string' like that.  It will
> lead to problems :-)
>
> You could do this:
>
> import string
> keepChars = string.letters + string.digits
>
> inStr = "@*&^$&[EMAIL PROTECTED](&@$*(&[EMAIL PROTECTED](*&*(&c^&%&^%"
> lst = [c for c in inStr if c in keepChars]
> outStr = ''.join(lst)
>   
Remember how people are always saying "don't use the string module 
unless necessary because string objects have most of the functionality 
built-in now"
This is another case of that.
teststr = "afdlkjal32jro3kjlkj(*&&^%&^TUHKLJDHFKJHS(*&987"
print ''.join([item for item in teststr if item.isalnum()])

No imports required, may be an abuse of isalnum since (I assume) this is 
generally intended for use on whole strings and not on single-character 
strings, but either way, it works.
Also note isalpha() and isdigit() for checking specific items in a string.
-Luke
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to