Is it possible to replace the same character with a unique random string in text file?

Question:

I’m using a function (I included the function below) that generates random strings and i need to replace for example [random] in my text file with a unique random string generated using that function, Example

My text file "text.txt" content is :
Papa [random] Eleven [random] NFT [random]

And I need such an output :
Papa 748F3G476F Eleven UF4H3637Y NFT UHD4367F4

I tried using .replace function to replace [random] by a random string generated with the function but I end up getting : Papa 7F47H46 Eleven 7F47H46 NFT 7F47H46

The random string generator function :

def my_random_string(string_length=8):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-","") # Remove the UUID '-'.
return random[0:string_length] # Return the random string.

Calling it to generate random string:

textfile = open("text.txt")
textcnt = tcrea.read()
textcnt.replace("[random]", my_random_string(6))

Thanks in advance!

Asked By: xamcx

||

Answers:

Use re.sub(). The replacement can be a function, so it can return a different value each time.

import re

textcnt = re.sub(r'[random]', lambda m: my_random_string(6), textcnt)
Answered By: Barmar

because they are all [random]

make it:

Papa [random1] Eleven [random2] NFT [random3]

then replace it all one by one

Answered By: Ebrahim Momin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.