Connor24
Connor24

Reputation: 23

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>
    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?

Upvotes: 0

Views: 14542

Answers (2)

Isaac Albets
Isaac Albets

Reputation: 1

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

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65811

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)

Upvotes: 2

Related Questions