KendoClaw
KendoClaw

Reputation: 47

Python - how to replace the same char in a string with random integer for each occurence

i have the following string for Example

str = "TESTXXXXX"

and i want to replace each X with a number, so the output should be something like this:

TEST98965

not :

TEST66666

i made the following python script to do the job.

from sys import argv
from random import randint

bincode = argv[1].lower()
replaced = bincode.replace('x',str(randint(0,9)))
print replaced

it takes a input from a user, and replaces each 'x' with a random number, the problem here is that the script replaces all the 'x' with the same number, i want each 'x' to be replaced with a different number, for example if user input is:

xxx

the output would be something like this:

986

Any suggestions on how to do that?

Upvotes: 2

Views: 1382

Answers (2)

wap26
wap26

Reputation: 2290

You can use the re.sub function which supports a function as the replacement. https://docs.python.org/2/library/re.html#re.sub

The function will be called for each match for the regex pattern and must produce the replacement.

s = "TESTXXXXX"

import re
import random

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

replaced = re.sub('X', repl_fun, s)
print replaced

# output example:
# TEST57681

Upvotes: 3

Mohammad Athar
Mohammad Athar

Reputation: 1980

you have to generate a new random integer every time

from sys import argv
from random import randint

bincode = argv[1].lower()
bc = ''
tgchar= 'x'

for c in bincode:
    #print(c) not sure why I put this
    if c != tgchar:
        bc = bc + (c)
    else:
        bc = bc + (str(randint(0,9)))

print(bc)

Upvotes: 1

Related Questions