Array of Chars to String
Bengt Richter
bokr at oz.net
Tue Apr 19 20:40:58 EDT 2005
On Tue, 19 Apr 2005 17:00:02 -0700, Michael Spencer <mahs at telcopartners.com> wrote:
>Michael Spencer wrote:
>> Bengt Richter wrote:
>> > 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'
>>>
>> According to my measurements the string doesn't have to be long at all
>> before your method is faster - cool use of str.translate:
>>
>...and here's a version that appears faster than "".join across all lengths of
>strings:
> >>> import string
> >>> def some_func1(s, letters, table=string.maketrans("","")):
> ... return s.translate(table, table.translate(table, letters))
> ...
> >>> some_func1("Bob Carol Ted Alice", "adB")
> 'Bad'
> >>>
>
Good one! ;-)
BTW, since str has .translate, why not .maketrans?
Anyway, this will be something to keep in mind when doing character-based joinery ;-)
>Timings follow:
Let's just say improved ;-)
(or see parent post)
Regards,
Bengt Richter
More information about the Python-list
mailing list