Inserting a string in a sliced string (Python)

Viewed 46

So I am pretty new in the programming world, I'm apologising in advance if that question has been answered a million time but I couldn't find an answer to my specific problem.

I'm making a simple password generator that take a list of words as input, for example:
test = ['carpe', 'diem']>
the desired output would be like
*7carZpe-hd_iemA:
So that's 2 randomly generated characters around and between each words and one in a random place in the word This second part is where i'm struggling.
In a terminal, when running python I can do :
test[0] = test[0][0:2] + '7' + test[0][2:]
So that carpe would now be ca7rpe and it works fine. Here are the two function I wrote to make it :
(I'm importing random and ascii_letters, digits, punctuation from string)

def random_generation(length):
    string = f'{ascii_letters}{punctuation}{digits}'
    string = list(string)
    random.shuffle(string)
    randomised = random.choices(string, k=length)
    randomised = ''.join(randomised)
    return randomised

def custom_generation(listOfWords):
    for words in range(0, len(listOfWords)):
        word = listOfWords[words]
        randomInsert = random.randint(0, len(word))
        word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

        
    for insertion in range(0, (len(listOfWords) * 2) + 1, 2):
        listOfWords.insert(insertion, random_generation(2))
    password = ''.join(listOfWords)
    return password

My guess is that I'm doing something wrong on the first for-loop but even after a couple modifications and try I couldn't find the way.

Thank you kindly !

2 Answers

If I am not mistaken your code is missing assignment of altered word back to list, try replacing

for words in range(0, len(listOfWords)):
    word = listOfWords[words]
    randomInsert = random.randint(0, len(word))
    word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

using

for words in range(0, len(listOfWords)):
    word = listOfWords[words]
    randomInsert = random.randint(0, len(word))
    listOfWords[words] = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

You are right. The mistake is in the first for loop. When you do

word = listOfWords[words]

you are copying the list element into a new variable. Anything that you do to this variable will not affect the list elements.

So all you have to do is, change

word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

to

listOfWords[words] = word[0:randomInsert] + random_generation(1) + word[randomInsert:]
Related