Array of Chars to String
Michael Spencer
mahs at telcopartners.com
Tue Apr 19 16:40:27 EDT 2005
James Stroud wrote:
> Hello,
>
> I am looking for a nice way to take only those charachters from a string that
> are in another string and make a new string:
>
>
>>>>astr = "Bob Carol Ted Alice"
>>>>letters = "adB"
>>>>some_func(astr,letters)
>
> "Bad"
>
> I can write this like this:
>
> astr = "Bob Carol Ted Alice"
> letters = "adB"
>
> import sets
> alist = [lttr for lttr in astr if lttr in Set(letters)]
> newstr = ""
> for lttr in alist:
> newstr += lttr
>
> But this seems ugly. I especially don't like "newstr += lttr" because it makes
> a new string every time. I am thinking that something like this has to be a
> function somewhere already or that I can make it more efficient using a
> built-in tool.
>
> Any ideas?
>
> James
>
How about:
>>> astr = "Bob Carol Ted Alice"
>>> letters = "adB"
>>> "".join(letter for letter in astr if letter in set(letters))
'Bad'
>>>
Michael
More information about the Python-list
mailing list