首页 > 解决方案 > 它只返回一个字母

问题描述

它只返回一个字母。但是我想在一行中返回所有字母,如果我循环返回,它会返回第一个字母。如果在循环外返回,则返回最后一个字母。

def cip(pas):
    for i in pas:
        asci = ord(i)
        encryption = asci + 4
        reverse = chr(encryption)
        return reverse

a = 'lipps'
b = 'hello'
if cip(b) == a:
    print('hey')

标签: pythonpython-3.x

解决方案


您在循环的早期返回,您需要建立一个字符串并返回它。要么只返回一个联合字符串,要么建立它

 "".join(chr(ord(s)+4) for s in pas)
def cip(pas):
    ret_val = ""
    for i in pas:
        asci = ord(i)
        encryption = asci + 4
        ret_val += chr(encryption)
    return ret_val

推荐阅读