Python TypeError: sequence item 0: expected str instance, NoneType found

强颜欢笑 提交于 2019-12-25 04:22:25

问题


I copied this code from a book:

lyst = {'Hi':'Hello'}
def changeWord(sentence):
    def getWord(word):
        lyst.get(word, word)
    return ''.join(map(getWord, sentence.split()))

I get this error:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    cambiaPronome('ciao')
  File "C:\Python33\2.py", line 6, in cambiaPronome
    return ''.join(map(getWord, list(frase)))
TypeError: sequence item 0: expected str instance, NoneType found

What is wrong?


回答1:


The getWord function doesn't explicitly return anything, so it implicitly returns None. Try returning something, e.g.:

def getWord(word):
    return lyst.get(word, word)



回答2:


The problem is you're trying to write to a string a type which is NoneType. That's not allowed.

If you're interested in getting the None values as well one of the things you can do is convert them to strings.

And you can do it with a list comprehension, like:

return ''.join([str(x) for x in map(getWord, sentence.split())])

But to do it properly in this case, you have to return something on the inner function, else you have the equivalent to return None



来源:https://stackoverflow.com/questions/25222697/python-typeerror-sequence-item-0-expected-str-instance-nonetype-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!