我正在尝试使用Caesar Code将一个字符串编码为不同的字符串
def encode(letters,code,word):
lettersTab = list(letters)
lettersTab = lettersTab*2
lenghtLetters = len(letters)
howMany = code%lenghtLetters
wordTab = list(word)
secondTab = [None]*len(word)
for j in range(0,len(word)):
for i in range(0,int(len(lettersTab)/2)):
secondTab[j] = wordTab[j].replace(lettersTab[i],lettersTab[i+howMany])
print(secondTab)
encode("bca",2,"abc")
这个输入意味着b转换成a,等等。b->;a,c->;b,a->;c
输出应为:
['c','a','b']
但确实如此
['b','b','c']
因为内部循环
for i in range(0,int(len(lettersTab)/2)):
在循环的每个步骤上将
secondTab[j]
设置为wordTab[j]
,即使wordTab[j]
与lettersTab[i]
不匹配,这不是您想要的。你知道吗注意,如果
oldstr
不包含a
,则newstr = oldstr.replace(a, b)
使newstr
=oldstr
。你知道吗下面是一个清理过的函数版本,加上一些渐进式的改进,最后一个示例使用了列表理解。我的一些版本使用
index()
,如果找不到它要找的东西,它会抛出一个异常,但是您的原始代码也遇到了类似的问题。你知道吗我更改了函数的名称,因为
encode
是python2(我正在运行)中的标准字符串函数。你知道吗希望您(或某人:)能从这些示例中了解更多关于Python的信息。。。你知道吗
相关问题 更多 >
编程相关推荐