Python Forum
basic random number generator in replace function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: basic random number generator in replace function (/thread-28712.html)



basic random number generator in replace function - krug123 - Jul-31-2020

Hey, I'm new to python and wanted to know how can I integrate a pseudo-random number generator to a replace function
for example how do I input something like "a) 245 V, b) 736.77 V." and print it with different numbers 3 times
thanks before hand :)


RE: basic random number generator in replace function - DPaul - Jul-31-2020

Without an output example, this is not very clear to me.
Paul


RE: basic random number generator in replace function - deanhystad - Jul-31-2020

Is an example needed? The question is, "Can I use random with replace()?" I take this to mean if we are doing string.replace(old, new) and there are multiple occurrences of "old" in "string", can he somehow use "random" to make a new "new" for each occurrence. I don't see how that can be done.

This obviously doesn't work:
import random
 
a = 'Now is the time for all good men to come to the aid of their country'
b = a.replace('t', random.choice(('A', 'B', 'C')))
print(b)
random.choice gets evaluated and the result is used for "new" in all the replacements.
Output:
Now is Ahe Aime for all good men Ao come Ao Ahe aid of Aheir counAry
I cannot think of a way that you can re-evaluate "new" for each replacement. I think you need to look for another solution to this particular problem.