python - 在切片字符串中插入字符串 (Python)

标签 python string slice

所以我在编程世界中还是个新手,如果这个问题已经被回答了一百万次但我找不到我的具体问题的答案,我提前道歉。

我正在制作一个简单的密码生成器,它将单词列表作为输入,例如:
测试 = ['carpe', 'diem']>
所需的输出如下
*7carZpe-hd_iemA:
所以这是每个单词周围和之间的 2 个随机生成的字符,以及单词中随机位置的一个字符第二部分是我正在努力的地方。
在终端中,运行 python 时我可以执行以下操作:
测试[0] = 测试[0][0:2] + '7' + 测试[0][2:]
这样 carpe 现在将是 ca7rpe 并且工作正常。 这是我编写的两个函数:
(我正在从字符串导入随机和 ascii_letters、数字、标点符号)

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

我的猜测是我在第一个 for 循环中做错了一些事情,但即使经过几次修改和尝试我也找不到方法。

谢谢您!

最佳答案

如果我没记错的话,您的代码缺少将更改后的单词返回到列表的分配,请尝试替换

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

关于python - 在切片字符串中插入字符串 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65916564/

相关文章:

python - grid() 是否有像 tkinter 中的 pack() 一样的 fill 属性?

php - 检查字符串是否在 PHP 中全部大写

string - 从 `&' 中获取比当前函数更长生命周期的 str` `String`

rust - 从 u8 切片创建读取特征对象

python - 在单个数据库调用中评估多个查询集

python - Django get_or_create 未在模型中创建新记录

c++ - 如何在 C++ 中实现与 unicode 无关的大小写不敏感比较

go - 无法使用 Go 在函数中覆盖列表类型接口(interface) {}

python - 在 Python 中对系列进行切片和索引

python - 有没有更好的方法(除了 COM)来远程控制 Excel?