Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #61417 > unrolled thread
| Started by | MRAB <python@mrabarnett.plus.com> |
|---|---|
| First post | 2013-12-09 21:08 +0000 |
| Last post | 2013-12-09 21:08 +0000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Possible PEP Submission MRAB <python@mrabarnett.plus.com> - 2013-12-09 21:08 +0000
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2013-12-09 21:08 +0000 |
| Subject | Re: Possible PEP Submission |
| Message-ID | <mailman.3799.1386623316.18130.python-list@python.org> |
On 09/12/2013 20: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?
>
What's your use-case? How often would someone want to do this?
Here's a way of doing it without adding to the re module:
import re
text = """hello user
hello user
hello user"""
class Replacement:
def __init__(self, users):
self.users = users
self.index = -1
def __call__(self, m):
self.index += 1
return self.users[self.index]
users = ["Bob", "Alice", "Jeffery"]
newtext = re.sub("user", Replacement(users), text)
# newtext = "hello Bob\nhello Alice\nhello Jeffery"
print(newtext)
The search string is a simple literal, so another way is:
from itertools import chain
text = """hello user
hello user
hello user"""
users = ["Bob", "Alice", "Jeffery"]
# newtext = "hello Bob\nhello Alice\nhello Jeffery"
newtext = "".join(chain(*zip(text.split("user", len(users)), users)))
print(newtext)
Back to top | Article view | comp.lang.python
csiph-web