[Tutor] Finding all the letters in a string?

John Fouhy john at fouhy.net
Tue Sep 18 02:43:24 CEST 2007


On 18/09/2007, Andrew Nelsen <sxkorean at gmail.com> wrote:
> I was wondering, recently, the most expedient way to take a string with
> [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$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 = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&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 = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%"
lst = [c for c in inStr if c in keepChars]
outStr = ''.join(lst)

-- 
John.


More information about the Tutor mailing list