[Python-ideas] Easily remove characters from a string.
Sjoerd Job Postmus
sjoerdjob at sjoerdjob.com
Tue Oct 25 02:57:41 EDT 2016
On Mon, Oct 24, 2016 at 05:37:29PM -0700, Chris Barker - NOAA Federal wrote:
> > On Oct 24, 2016, at 3:54 PM, Chris Angelico <rosuav at gmail.com> wrote:
>
> > . But in any case,
> > this is a question you can't even ask until replace() accepts multiple
> > arguments. Hence I'm +1 on the notion of simultaneous replacements
> > being supported.
>
> Agreed -- there are a lot of edge cases to work out, and there is not
> one way to define the API, but if folks think it's a good idea, we can
> hash those out.
>
> If anyone decides to take this on, be prepared for a lot of bike shedding!
Regarding prior art, I think that the PHP ``strtr`` function is a good
example:
http://php.net/manual/en/function.strtr.php
Especially with regards to the ``replace_pairs`` argument:
If given two arguments, the second should be an array in the form
array('from' => 'to', ...). The return value is a string where all
the occurrences of the array keys have been replaced by the
corresponding values. The longest keys will be tried first. Once a
substring has been replaced, its new value will not be searched
again.
This is one I have sometimes used when writing a mini template language,
where `{{ username }}` had to be replaced. In contrast to other ways,
``strtr`` gives a one-pass garantuee, which means that it was safe
against hypothetical attacks where one would add a template-string to
one of the values.
More information about the Python-ideas
mailing list