首页 > 解决方案 > 代码抛出错误:只能将 str(不是“NoneType”)连接到 str

问题描述

它似乎在为空时可能正在运行S,但它不应该因为我的第if一句话。

它在第 15 行抛出错误:只能将str(不是“NoneType”)连接到str.

def encipher(S, n):
    """
    Returns a forward shifted string based on the rules of caesar cipher
    Argument S: String to be shifted
    Argument n: number of spaces shifted
    """

    if len(S) > 0:  
        if ord("a")<=ord(S[0])<=ord("z"):   #lowercase letters
            if ord("a") <= ord(S[0])+n <= ord("z"):   #if the shifter letter is in the alphabet range add
                return rot(S[0],n) + encipher(S[1:],n)
            else:                                   #else subtract
                return rot(S[0],(n-26)) + encipher(S[1:],n)
        elif ord("A")<=ord(S[0])<=ord("Z"):   #uppercase letters
            if ord("A") <= ord(S[0])+n <= ord("Z"): #if the shifter letter is in the alphabet range add
                return rot(S[0],(n)) + encipher(S[1:],n)
            else:                               #else subtract
                return rot(S[0],(n-26)) + encipher(S[1:],n) 
        else:
            return S[0] + encipher(S[1:],n)
    else:
        return 
        
def rot(c, n):
    #shifts a character
    if len(c)>0:
        return chr(ord(c)+n)
    else: 
        return 

标签: python

解决方案


只需None将它们更改为 string( "") 就可以了。

def encipher(S, n):
    """
    Returns a forward shifted string based on the rules of caesar cipher
    Argument S: String to be shifted
    Argument n: number of spaces shifted
    """

    if len(S) > 0:
        if ord("a") <= ord(S[0]) <= ord("z"):  # lowercase letters
            if ord("a") <= ord(S[0]) + n <= ord("z"):  # if the shifter letter is in the alphabet range add
                return rot(S[0], n) + encipher(S[1:], n)
            else:  # else subtract
                return rot(S[0], (n - 26)) + encipher(S[1:], n)
        elif ord("A") <= ord(S[0]) <= ord("Z"):  # uppercase letters
            if ord("A") <= ord(S[0]) + n <= ord("Z"):  # if the shifter letter is in the alphabet range add
                return rot(S[0], (n)) + encipher(S[1:], n)
            else:  # else subtract
                return rot(S[0], (n - 26)) + encipher(S[1:], n)
        else:
            return S[0] + encipher(S[1:], n)
    else:
        return ""


def rot(c, n):
    # shifts a character
    if len(c) > 0:
        return chr(ord(c) + n)
    else:
        return ""

S = "b"
n = 3
print(encipher(S, n))

输出:

e

推荐阅读