Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace non-numeric characters in string

I would like to know how to replace non-numeric characters in a single string with different random integers.

I have tried the following:

text = '1$1#387'
rec_1 = re.sub("\D+",str(random.randint(0,9)),text)

It then produced:

output: 1717387 

As you can see, the non-numeric characters have been replaced by the same integer. I would like each non-numeric character to be replaced by a different integer. For example:

desired output: 1714387

Please assist.

like image 697
Mbali_c Avatar asked Dec 30 '25 05:12

Mbali_c


2 Answers

Use a function as the replacement value:

def replacement(match):
    return str(random.randint(0, 9))

text = '1$1#387'
rec_1 = re.sub(r"\D", replacement, text)

rec_1 is now "1011387", or "1511387", ...

like image 109
L3viathan Avatar answered Dec 31 '25 18:12

L3viathan


That's because the randint function is called only 1 time.
You can use a lambda to get a new randint each time:

rec_1 = re.sub("\D+", lambda x: str(random.randint(0, 9)), text)
like image 41
Gsk Avatar answered Dec 31 '25 19:12

Gsk