2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

very nice; use a lambda function and it'll be even more concise! replaced = re.sub('X', lambda x: str(random.randint(0,9)), s)
fantastic, but i have a question here, why did you set repl_fun() to take 1 argument and when calling it you didn't insert any arguments?
@KendoClaw the replacement function is required to accept a single argument (the re.match object). In your case the replacement does not dependent on the matched text, so the argument is ignored.
1

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)

2 Comments

thank you for replying, this script prints each char in a new line, i don't want this, i want it all in the same string so i can save it to a file if i want.
it prints some characters because of the (now commented out) print statement. at the end, it should print out the new string (the last line that says print(bc) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.