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

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>
  File "C:Python332.py", line 6, in cambiaPronome
    return ''.join(map(getWord, list(frase)))
TypeError: sequence item 0: expected str instance, NoneType found

What is wrong?

Enquirer: Connor24


Solution #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)
Respondent: Lev Levitsky

Solution #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

Respondent: Isaac Albets

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.