UKDP UKDP - 3 months ago 8
Python Question

Python: Count character in string which are following each other

I have a string in which I want to count the occurrences of

#
following each other to replace them by numbers to create a increment.

For example:

rawString = 'MyString1_test##_edit####'

for x in xrange(5):
output = doConvertMyString(rawString)
print output

MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004
MyString1_test05_edit0005


Assuming that the number of
#
is not fixed and that
rawString
is a user input containing only
string.ascii_letters + string.digits + '_' + '#
, how can I do that?

Here is my test so far:

rawString = 'MyString1_test##_edit####'
incrDatas = {}
key = '#'
counter = 1

for x in xrange(len(rawString)):
if rawString[x] != key:
counter = 1
continue
else:
if x > 0:
if rawString[x - 1] == key:
counter += 1
else:
pass
# ???

Answer

You may use zfill in the re.sub replacement to pad any amount of # chunks. #+ regex pattern matches 1 or more # symbols. The m.group() stands for the match the regex found, and thus, we replace all #s with the incremented x converted to string padded with the same amount of 0s as there are # in the match.

import re
rawString = 'MyString1_test##_edit####'
for x in xrange(5):
    output = re.sub(r"#+", lambda m: str(x+1).zfill(len(m.group())),  rawString)
    print output

Result of the demo:

MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004
MyString1_test05_edit0005
Comments