Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

Inserting a string in a sliced string (Python)

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 !

question from:https://stackoverflow.com/questions/65916564/inserting-a-string-in-a-sliced-string-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...