首页 > 解决方案 > 如何在字符串中插入随机字符

问题描述

我正在编写一个程序来打乱字符串。程序应反转输入字符串,并每隔 6 个字符插入一个随机符号。

这是我所拥有的:

word =  input("Type the string to ecrypted  ")
symbols = list("!@#$%^&*()1234567890_-+=")
word = word[::-1]

for letter in word:
    if letter % 2 == 0 and letter % 3 == 0:
        # what do I put here??????????????
print(word)

我被困在如何将随机字符插入字符串中。

标签: pythonencryption

解决方案


Python 中的字符串是不可变的,因此您需要创建新字符串来组合来自的字符word和随机符号。

在测试是否插入随机字符时,您需要使用索引,而不是字符。您可以使用enumerate().

如果要在每个 2 的倍数和每个 3 的倍数之后插入随机字符,则需要使用or,而不是and

import random

word =  input("Type the string to ecrypted  ")
symbols = list("!@#$%^&*()1234567890_-+=")
word = word[::-1]

encrypted = ""
for index, letter in enumerate(word):
    encrypted += letter
    if index % 2 == 0 or index % 3 == 0:
        encrypted += random.choice(symbols)
print(encrypted)

推荐阅读