mardi 2 janvier 2018

Replace `{}` in string with hexadecimal values

I have a string with random stuff in it, for e.g:

random_string = """

asdasdasd23123asdnos{}n
asdnoiaf{}aosndiasdasd
asd{}1239i123nig
hpodpfh{}askmdiasd
{asdasda
}asdasdasd
"""

I would like to replace every occurrence of {} in that string with a random hexadecimal value that is different from the previous values that replaced the other curly brackets.

I am using this function to generate hexadecimal values that are 100% random.

def get_random(n):
    out = set()
    while len(out) < n:
        out.add(binascii.b2a_hex(os.urandom(1)))
    return list(out)

I am missing a function or a loop, in which, the value of the hexadecimal is taken from the list get_random(n), replacing {} in the string with the value of the hex from the list and printing out the output.

I was using the module re, but not all values are random, there is a high chance some of the values are alike.

print(re.sub('{}', lambda _: binascii.b2a_hex(os.urandom(1)) + ' \\', random_string))

Any help is appreciated!




Aucun commentaire:

Enregistrer un commentaire