473,396 Members | 1,895 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Iteration within re.sub()?

Hi,

Is it possible to perform iteration within the re.sub() function call?

For example, if I have a string like:

str = "abbababbabbaaa"

and I want to replace all b's with an integer that increments from 0,
could I do that with re.sub()?

Replacing b's with 0's is trivial:

i = 0
pat = re.compile("b")
print pat.sub(`i`, str)

Now, how can I increment i in each replacement? Is this possible? Like,
using a lambda function, for example? Or do I use a different re
function altogether?

I use this trivial [ab]* language for simplicity, but I have a real
problem where I need to match a more complex regex and replace it with
an incrementing integer.

Thanks so much!
Bryant

Jul 18 '05 #1
3 5158
Bryant Huang wrote:
Hi,

Is it possible to perform iteration within the re.sub() function call?

Sure. As the docs note:

If repl is a function, it is called for every non-overlapping occurrence
of pattern. The function takes a single match object argument, and
returns the replacement string. For example:

#!/usr/bin/env python

import re

class Counter:
def __init__(self):
self.count = -1
def increment(self, matchObject):
self.count += 1
return str(self.count)

text = "abbababbaaaaaabbaaa"
expected = "a01a2a34aaaaaa56aaa"

# Replace all b's with an integer that increments from 0.

c = Counter()
pat = re.compile("(b)")
actual = pat.sub(c.increment, text)
assert expected == actual

Jul 18 '05 #2
Ah beautiful, thank you both, Robert and Mark, for your instant and
helpful responses. I understand, so the basic idea is to keep a
variable that is globally accessible and call an external function to
increment that variable...

Thanks!
Bryant

Jul 18 '05 #3
Bryant Huang wrote:
Ah beautiful, thank you both, Robert and Mark, for your instant and
helpful responses. I understand, so the basic idea is to keep a
variable that is globally accessible and call an external function to
increment that variable...


accessible for the callback function, that is.

see Mark's example for the right way to do it (using a object to hold
the state, and an object method as the callback -- the latter is known
as a "bound method", and holds a reference to both the data (self) and
the code).

</F>

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Philippe Rousselot | last post by:
Hi, How do I find the second iteration of a character in a string using python this gives me the first one f1 = string.find(line,sub) this the last one f2 = string.rfind(line,sub)
35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
2
by: Abdullah Khaidar | last post by:
Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def...
2
by: Gman | last post by:
Hi, I have created a usercontrol, a grid control essentially. Within it I have a class: clsGridRecord. I have coded the events such that when a user clicks on the grid, say, the events occur on...
28
by: robert | last post by:
In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are...
2
by: Al Reid | last post by:
I'm using VB 2005. I have a production application where I load a ListView with information from several sources based on user interaction. At some point I need to iterate through the Items...
9
by: news.microsoft.com | last post by:
I am looping through an iteration and I would like to test the next item but if its not the one that I want how do I put it back so that when my foreach continues it is in the next iteration? ...
0
by: ChopStickr | last post by:
I have a custom control that is embedded (using the object tag) in an html document. The control takes a path to a local client ini file. Reads the file. Executes the program specified in...
5
by: hurricane_number_one | last post by:
I'm trying to have a class, which uses threads be able to raise events to the form that created it. I've seen solutions around the net for this, but I didn't really like their implementation. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.