Array of Chars to String

Bengt Richter bokr at oz.net
Tue Apr 19 19:07:42 EDT 2005


On Tue, 19 Apr 2005 13:33:17 -0700, James Stroud <jstroud at mbi.ucla.edu> 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
>
I think this will be worth it if your string to modify is _very_ long:

 >>> def some_func(s, letters, table=''.join([chr(i) for i in xrange(256)])):
 ...     return s.translate(table,
 ...            ''.join([chr(i) for i in xrange(256) if chr(i) not in letters]))
 ...
 >>> some_func("Bob Carol Ted Alice", 'adB')
 'Bad'

see help(str.translate)

If you want to use it in a loop, with the same "letters" I'd want to eliminate the repeated
calculation of the deletions. You could make a factory function that returns a function
that uses deletions from a closure cell. But don't optimize prematurely ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list