Python为什么这个for循环只打印1个字母?

2024-05-08 13:49:12 发布

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

def caesar(plaintext,shift):  
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]  

    #Create our substitution dictionary  
    dic={}  
    for i in range(0,len(alphabet)):  
        dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]  

    #Convert each letter of plaintext to the corrsponding  
    #encrypted letter in our dictionary creating the cryptext  
    ciphertext=("")  
    for l in plaintext.lower():  
            if l in dic:  
                l=dic[l]  
                ciphertext+=l
            return ciphertext  

#Example useage  
plaintext="the cat sat on the mat"  
print "Plaintext:", plaintext  
print "Cipertext:", (caesar(plaintext,29)) 

cipertext只打印一个字母,而不是在caesar shift中打印“明文”变量。我要它把整个句子打印出来。在

谢谢


Tags: theinfordictionarylenshiftdefour
3条回答

用它做得更好字符串.翻译:)

import string
def caesar(plaintext,shift):  
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    alphabet_shifted = alphabet[shift:]+alphabet[:shift]
    tab =    string.maketrans("".join(alphabet),"".join(alphabet_shifted))
    return plaintext.translate(tab)

您需要修复return语句的缩进:

for l in plaintext.lower():  
    if l in dic:  
       l=dic[l]  
       ciphertext+=l
    # <  if you return here, then you will loop only once.      
return ciphertext  

这是因为您的return ciphertext缩进错误。从for循环的第一次迭代返回。(缩进在Python中非常重要!)在

    for l in plaintext.lower():  
            if l in dic:  
                l=dic[l]  
                ciphertext+=l
            return ciphertext  # Indented to match level of `if`.

把它固定到。在

^{pr2}$

几个指针

  1. 不用列出代码中的所有字母表,您只需设置alphabets = string.ascii_lowercase。在
  2. 不需要变量来存储dic[l],只需ciphertext += dic[l]。在

相关问题 更多 >

    热门问题