[Python-ideas] str.find() and friends support a lists of inputs
Steven D'Aprano
steve at pearwood.info
Fri Apr 18 04:22:22 CEST 2014
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.
Although this is easily done using a regex, it does require the user
learn about regexes, which may be overkill. They have a steep learning
curve and can be intimidating to beginners. In order of preference, I'd
prefer:
+1 allow str.find, .index and .replace to take tuple arguments to search
for multiple substrings in a single pass;
+0.5 to add helper functions in the string module findany replaceany.
(No need for an indexany.)
-0 tell the user to "just use a regex".
(Perhaps we could give a couple of regex recipes in the Python FAQ or
the re docs?)
--
Steven
More information about the Python-ideas
mailing list