[Python-ideas] string.replace should accept a list as a first argument

Matthew Einhorn moiein2000 at gmail.com
Tue Oct 6 21:40:55 CEST 2015


On Tue, Oct 6, 2015 at 1:35 PM, Sven R. Kunze <srkunze at mail.de> wrote:

> ...
> Speaking of "replace", sometimes, I would love to pass an "replace all of
> these with all of those" dict, which is then processed internally. I can
> remember two times where we needed to write some kind of for-loop; which
> actually might produce wrong results:
>
> convert_dict = {
>     '1': '2',
>     '2': '3',
> }
> original = '12345'
> for from_, to in convert_dict.items():
>     original = original.replace(from_, to)
>

Also, you can do:

  re.sub('|'.join(convert_dict.keys()), lambda x: convert_dict[x.group(0)],
original)

Which is probably better as it performs the match at once. But of course
you have to know ahead of time what the keys of the dict may be as they
need to be escaped etc.

Matt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151006/ba3f46c8/attachment.html>


More information about the Python-ideas mailing list