使用ord函数对字符串排序

我正在尝试使用ord函数拆分字符串。这是我的代码

def sortString(info):
    res = isinstance(info, str)
    if res:
        for char in info:
            charValue = ord(char)

            #Lowercase
            if charValue > 96 and charValue < 123:
                lChar += char

            #Uppercase   
            elif charValue > 64 and charValue < 91:
                cChar += char

            #Punctuation
            elif charValue > 32 and charValue < 65:
                pChar += char

            #Spaces
            elif charValue == 32:
                numSpace += 1

            result = "cChar\nlChar\npChar\nnumSpace"

            return result
    else:
        return "Not a string!"

我希望它根据大写字母,小写字母,标点符号和空格数来分割字符串。所以“你好,世界!”将输出:

硬件 elloorld ,!! 1个

我现在得到的错误是UnboundLocalError:分配前引用了本地变量'cChar'。我试图制作一个空字符串,但这并不能解决问题。

评论
  • 菊花残
    菊花残 回复

    You are updating cChar before initialising it and also lChar and pChar

    def sortString(info):
        res = isinstance(info, str)
        if res:
            # INITIALISING
            cChar = lChar = pChar = ""
            for char in info:
                charValue = ord(char)
    
                #Lowercase
                if charValue > 96 and charValue < 123:
                    lChar += char
    
                #Uppercase   
                elif charValue > 64 and charValue < 91:
                    cChar += char
    
                #Punctuation
                elif charValue > 32 and charValue < 65:
                    pChar += char
    
                #Spaces
                elif charValue == 32:
                    numSpace += 1
    
                result = "cChar\nlChar\npChar\nnumSpace"
    
                return result
        else:
            return "Not a string!"