我正在写一个程序来置乱字符串。程序应反转输入字符串,并每隔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)
我一直在研究如何在字符串中插入随机字符
Python中的字符串是不可变的,因此需要创建新字符串来组合来自
word
的字符和随机符号测试是否插入随机字符时,需要使用索引,而不是字符。您可以使用
enumerate()
获取索引和字符如果要在2的每一个倍数之后以及3的每一个倍数之后插入随机字符,则需要使用
or
,而不是and
我想我大致可以看出你的意图,但如果我错了,请纠正我:
您希望通过反转输入字符串对消息进行置乱,并每6个字符添加一个随机符号
您已经反转了字符串,并且正在对每个字符进行迭代,但是没有弄清楚如何使用随机符号构建新字符串
如果要计算每6个字符的数量,除了字符本身之外,还需要一个数字来跟踪每个字符。为此,在
for
循环中使用enumerate
函数非常方便。然后,您可以使用数学计算您是否在第6个字符上:从这里开始,您需要开始构建新的输出字符串(您只能在python中创建新字符串,而不能修改现有字符串。覆盖变量可能看起来像修改现有字符串,但在内部,它会在覆盖现有字符串之前创建一个完整的新字符串,这就是为什么您不能执行以下操作:
my_string[3] = 'G'
). 为此,我们将创建一个变量,并按以下顺序添加字符:现在,为了获得一个随机符号来添加每6个字符,我们将通过在脚本开头调用
import random
来使用random
库。random.choice()
函数将从符号列表中选择一个随机元素,然后将其添加到我们正在构建的new_word
中相关问题 更多 >
编程相关推荐