Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding Random Characters Between Characters in a String (Python)

I’m trying to add random letters after each letter in a given range, but they aren’t in complete randomness.

def add_letters(org,num):
    new_word = ''
    for i in org:
        randomLetter = random.choice(string.ascii_letters) * num
        new_word += i
        new_word += randomLetter
    return new_word

original = 'Hello!'
for num in range(1,5):
    #scramble the word using 'num' extra characters
    scrambled = add_letters(original,num)
    #output
    print("Adding",num,'random characters to',original,'->',scrambled)

some of the results will have the same letter repeating multiple times like "HAAAAeiiiilzzzzlBBBBoSSSS!jjjj". Instead, they should be random.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • You used *sum, which only generate randomLetter once and repeat the result letter for sum times. It’s not repeat the random generation. So the result repeated.
  • It should be a loop or list-comprehension to generate mutiple randomLetter.

fixed code:

import random
import string
def add_letters(org,num):
    new_word = ''
    for i in org:
        randomLetter = "".join(random.choice(string.ascii_letters) for _ in range(num))
        new_word += i
        new_word += randomLetter
    return new_word

original = 'Hello!'
for num in range(1,5):
    #scramble the word using 'num' extra characters
    scrambled = add_letters(original,num)
    #output
    print("Adding",num,'random characters to',original,'->',scrambled)

result:

Adding 1 random characters to Hello! -> HNemldlgos!z
Adding 2 random characters to Hello! -> HVTeGYlYLlxdonV!GM
Adding 3 random characters to Hello! -> HqjbeQyOlgfHlAwqoyCj!PRq
Adding 4 random characters to Hello! -> HyFoLeyHUzlExGelVLlAoOhyz!EuzW
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading