如何在字符串中插入随机字符

2024-10-04 05:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来置乱字符串。程序应反转输入字符串,并每隔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)

我一直在研究如何在字符串中插入随机字符


Tags: theto字符串程序forinputstringtype
2条回答

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)

我想我大致可以看出你的意图,但如果我错了,请纠正我:

您希望通过反转输入字符串对消息进行置乱,并每6个字符添加一个随机符号

您已经反转了字符串,并且正在对每个字符进行迭代,但是没有弄清楚如何使用随机符号构建新字符串

如果要计算每6个字符的数量,除了字符本身之外,还需要一个数字来跟踪每个字符。为此,在for循环中使用enumerate函数非常方便。然后,您可以使用数学计算您是否在第6个字符上:

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

从这里开始,您需要开始构建新的输出字符串(您只能在python中创建新字符串,而不能修改现有字符串。覆盖变量可能看起来像修改现有字符串,但在内部,它会在覆盖现有字符串之前创建一个完整的新字符串,这就是为什么您不能执行以下操作:my_string[3] = 'G'). 为此,我们将创建一个变量,并按以下顺序添加字符:

new_word = '' #empty string
for index, letter in enumerate(word):
    new_word = new_word + letter
    if index % 2 == 0 and index % 3 == 0:
        # what do I put here??????????????
print(new_word)

现在,为了获得一个随机符号来添加每6个字符,我们将通过在脚本开头调用import random来使用random库。random.choice()函数将从符号列表中选择一个随机元素,然后将其添加到我们正在构建的new_word

new_word = '' #empty string
for index, letter in enumerate(word):
    new_word = new_word + letter
    if index % 2 == 0 and index % 3 == 0:
        random_char = random.choice(symbols)
        new_word = new_word + random_char
print(new_word)

相关问题 更多 >