Python Forum
basic random number generator in replace function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
basic random number generator in replace function
#3
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.
Reply


Messages In This Thread
RE: basic random number generator in replace function - by deanhystad - Jul-31-2020, 01:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Information Is it possible to multi line a Basic Function Construct line statement? If so how? BrandonKastning 7 413 May-23-2024, 03:02 PM
Last Post: deanhystad
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,603 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Noob here. Random quiz program. Using a while loop function and alot of conditionals. monkeydesu 6 1,553 Sep-07-2022, 02:01 AM
Last Post: kaega2
  matrix number assignement to the random indices juniorcoder 4 2,056 Feb-19-2022, 02:18 PM
Last Post: juniorcoder
  Tuple generator, and function/class syntax quazirfan 3 4,103 Aug-10-2021, 09:32 AM
Last Post: buran
  Random coordinate generator speed improvement saidc 0 2,124 Aug-01-2021, 11:09 PM
Last Post: saidc
  Generate random hex number ZYSIA 1 12,057 Jul-16-2021, 09:21 AM
Last Post: DeaD_EyE
  Checking the number of arguments a function takes Chirumer 3 2,286 Jul-06-2021, 04:56 PM
Last Post: Chirumer
  Random Number Repeating Tzenesh 5 4,171 Jan-13-2021, 10:00 PM
Last Post: deanhystad
  is there a single function to confine a number between two others? Skaperen 7 2,962 Nov-28-2020, 06:10 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020