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

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to