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.
*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.loop
or list-comprehension
to generate mutiple randomLetter
.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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.