String Python如何处理字符串等于无时的拆分?

String Python如何处理字符串等于无时的拆分?,string,python-3.x,split,String,Python 3.x,Split,这是我的代码来计算字符串中的单词现在工作正常,但是当我设置 def SetLength(passedString): wordlength = passedString.split() print(passedString) print(len(wordlength)) SetLength("Python code to count the words") 这显示了这样的错误 str = None SetLength(str) 有人能帮我吗 首先,您应该指定Set

这是我的代码来计算字符串中的单词现在工作正常,但是当我设置

def SetLength(passedString):
    wordlength = passedString.split()
    print(passedString)
    print(len(wordlength))

SetLength("Python code to count the words")
这显示了这样的错误

str = None

SetLength(str)

有人能帮我吗

首先,您应该指定SetLength()的确切功能。如果调用时没有参数,它应该做什么

如果它应该处理这个问题,那么相应地更改实现


如果不允许“无”,则相应地更改调用代码。

一个快速解决方案是添加一个If:

'NoneType' object has no attribute 'split'

当然,这也可以在调用
SetLength()
之前完成,这样在
passedString
为None时就不会调用
SetLength()

错误完全有效

无法对无对象调用.split,因为它没有该属性

您需要在此处执行以下两项操作之一:

  • 您可以检查对象是否为“真实”:

    i、 e:

    ...
    if not passedString:
        passedString = ""
    ...
    
    def SetLength(passedString):
        if passedString:
            wordlength = passedString.split()
            return len(wordlength)
    
        # if it's none, it will come here...
        # you probably want to return 0 as the length of words at that point
        return 0
    
    注意:对于空字符串“”,这也将返回0;这是意料之中的

  • 您可以使用“isinstance”确保对象是字符串:

    i、 e:

    ...
    if not passedString:
        passedString = ""
    ...
    
    def SetLength(passedString):
        if passedString:
            wordlength = passedString.split()
            return len(wordlength)
    
        # if it's none, it will come here...
        # you probably want to return 0 as the length of words at that point
        return 0
    

  • 如果需要字符串,为什么要将
    None
    传递到
    SetLength
    中?我正在从json文件调用string对象,如果有时候json没有字符串类型,我的代码必须处理这种情况。对不起,情况是输入不确定它是否可以为Null(None),我的代码不应该崩溃,它应该返回0。谢谢,现在,如果我们不确定输入类型,比如它可以是object,也可以是dictionary,也可以是integer。所以我们检查类型,而不是字符串,我们输入它。如果它是dictionary,那么它会是什么样子?您需要了解字典结构,才能将其转换为字符串。。如果它是一个整数,那么如果isinstance(passedString,int),单词的长度总是1:返回1这非常混乱。如果你不确定你得到的是一个字符串还是一个字符串都没有,那么也许你应该重新审视你想要实现的目标。。。更多的了解可能会有所帮助。问题是我正在从json外部调用一个对象,在这种情况下,我不确定那里有什么类型的数据,它可能是一个字符串、整数和无,您的代码帮助我处理无,非常感谢