Possible PEP Submission

Tim Chase python.list at tim.thechases.com
Mon Dec 9 16:01:22 EST 2013


On 2013-12-09 14:36, Logan Collins wrote:
> Just checking whether 1) a PEP is the proper place for this and 2)
> what y'all think about it.
> 
> I would like to propose a change to the the 're' standard library to
> support iterables.
> 
> So, something like the following would work:
> 
> import re
> text = """hello user
> hello user
> hello user"""
> 
> users = ["Bob", "Alice", "Jeffery"]
> 
> newtext = re.sub("user", users, text)
> 
> # newtext = "hello Bob\nhello Alice\nhello Jeffery"
> 
> There are a few corner cases I'm not sure what would be the best
> behavior. Nor am I entirely certain this should be modified
> functionality or just... a new function. What do y'all think?

Well, it's not that hard to do in stock python:

  i = itertools.cycle(users)
  print re.sub(
    'user',
    lambda m: next(i),
    text
    )

which should handle both the "fewer matches than items in users"
case, as well as wrap around in the "more matches than items in
users" case.  If you don't want wrap-around, just use iter(users)
instead of itertools.cycle(users)

This could be wrapped up in some class to give it a clearer name, but
I'm not sure it's worth doing a PEP or even including it in the
standard library.

-tkc







More information about the Python-list mailing list