[Python-ideas] Give regex operations more sugar

MRAB python at mrabarnett.plus.com
Wed Jun 13 18:54:34 EDT 2018


On 2018-06-13 21:52, Chris Angelico wrote:
> On Thu, Jun 14, 2018 at 6:43 AM, Michel Desmoulin
> <desmoulinmichel at gmail.com> wrote:
>>
>>
>> Le 13/06/2018 à 19:11, Mike Miller a écrit :
>>>
>>> On 2018-06-13 06:33, Michel Desmoulin wrote:
>>>>
>>>> I often wished for findall and sub to be string methods, so +1 on that.
>>>>
>>>
>>> Agreed, and there are a few string functions that could be extended (to
>>> take a sequence) to handle more cases that push folks to regex, perhaps
>>> earlier than they should.
>>
>> str.replace come to mind. It's a annoying to have to chain it 5 times
>> while we could pass optionally a tuple.
> 
> That would be handy. Either pass two sequences of equal length
> (replace each with the corresponding), or one sequence and one string
> (replaceactual any with that). (And yes, I know that a string IS a
> sequence.) This would want to be semantically different from chained
> calls, in that a single replace([x,y,z], q) would avoid re-replacing;
> but for many situations, it'll be functionally identical.
> 
Would it check first-to-last or longest-to-shortest? I think that 
longest-to-shortest would be the most useful.

 >>> old = ('cat', 'cats')
 >>> new = ('mouse', 'mice')
 >>>
 >>> # First-to-last.
 >>> 'cats'.replace(old, new)
'mouses'
 >>>
 >>> # Longest-to-shortest.
 >>> 'cats'.replace(old, new)
'mice'

[snip]


More information about the Python-ideas mailing list