[Python-ideas] in str.replace(old, new), allow 'old' to accept a tuple

Stefan Behnel stefan_ml at behnel.de
Thu Apr 12 19:08:58 CEST 2012


INADA Naoki, 12.04.2012 18:32:
> On Fri, Apr 13, 2012 at 1:20 AM, Sven Marnach wrote:
>> INADA Naoki schrieb am Thu, 12. Apr 2012, um 22:17:30 +0900:
>>> Oh, I didn't know that. Thank you.
>>> But what about unescape? str.translate accepts only one character key.
>>
>> You'd currently need to use the `re` module:
>>
>>    >>> d = {"&": "&", ">": ">", "<": "<"}
>>    >>> re.sub("|".join(d), lambda m: d[m.group()], "<>&")
>>    '<>&'
>
> Yes, I know it.
> But if str.replace() or str.translate() can do it, it is simpler and
> faster than re.sub().

Simpler, maybe, at least at the API level. But faster? Not necesarily. It
could use Aho-Corasick, but that means it needs to construct the search
graph on each call, which is fairly expensive. And str.replace() isn't the
right interface for anything but a one-shot operation if the intention is
to pass in a sequence of keywords.

Stefan




More information about the Python-ideas mailing list