[Python-ideas] str.find() and friends support a lists of inputs

Ron Adam ron3200 at gmail.com
Sat Apr 19 03:40:35 CEST 2014



On 04/17/2014 10:22 PM, Steven D'Aprano wrote:
> On Thu, Apr 17, 2014 at 09:31:24PM -0400, Terry Reedy wrote:
>> >On 4/17/2014 2:52 PM, Alex Rodrigues wrote:
>>> > >It's a fairly common problem to want to .find() or .replace() or .split()
>>> > >any one of multiple characters.
>>> > >Currently the go to solution are:
>> >
>> >For replace, you left out the actual solution.
>> >
>>>>> > >>>telnum = '(800), 555-1234'
>>>>> > >>>telnum.translate(str.maketrans('','','(- ,)'))
>> >'8005551234'
> That solution only works when you want to replace single characters. It
> doesn't help to replace generic substrings:
>
> "That's one small step for a man, one giant leap for mankind.".replace(
>      'man', 'person')
>
> Naively looping over your input may not work.
>
> for term in (a, b, c):
>      s = s.replace(term, x)
>
>
> is not always the same as doing the replacements in a single pass. It
> seems like it ought to be the same, until you run into a situation like
> this:
>
> py> recipe = "Add one capsicum to the stew..."
> py> for term in ("capsicum", "chilli pepper", "pepper"):
> ...     recipe = recipe.replace(term, "bell pepper")
> ...
> py> print(recipe)
> Add one bell bell pepper to the stew...
>
>
> Oops! If the search terms are not known until runtime, you may have a
> lot of difficulty doing the replacements in an order that doesn't cause
> problems like this. There are ways around this problem, but they're
> tricky to get right.


Possible start by allowing the sep argument for str.partition accept a tuple.

      recipe, _recipe = "", recipe
      while _recipe:
          head, sep, _recipe = _recipe.partition(
                       ("capsium", "Chilli pepper", "pepper"))
          if sep:
              recipe = "".join([recipe, head, "bell pepper"])
          else:
              recipe = "".join([recipe, head])

Then maybe the other methods can use str.partition to do the work.

Cheers,
    Ron



More information about the Python-ideas mailing list