473,543 Members | 2,034 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5174
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 = "abbababbaaaaaa bbaaa"
expected = "a01a2a34aaaaaa 56aaa"

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

c = Counter()
pat = re.compile("(b) ")
actual = pat.sub(c.incre ment, 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
1595
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
3702
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 ------------------------------------------------------------- PEP: 323
2
2065
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 useListIteration(): list = result = "" for item in list: result += item return result
2
1683
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 the parent form. This is fine. The problem occurs when I want to raise an event for a user clicking on one of the clsRecords which are on the...
28
7341
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 "good" in such terms, that this core data structure is changed only by atomic operations, so that the data structure is always consistent regarding...
2
2398
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 collection and print the documents that have been requested. The contents of the ListView are never sorted or manipulated in any way. Occasionally the...
9
4029
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? Bill
0
1931
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 the ini on the client's PC. After the program has ended the control looks in a client side temp folder (specified by the ini file) for an image created...
5
2635
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. Most involve passing the form into the class, or require a lot of coding. All I really need to do is be able to have my thread call a function within...
0
7594
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5889
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4899
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3394
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1830
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
648
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.