0

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?

6
  • 1
    return ''.join(map(getWord, list(frase))) is not from the book. Why don't you show us the actual code you wrote? Commented Aug 9, 2014 at 20:26
  • You are not returning anything from the getWord method. Commented Aug 9, 2014 at 20:26
  • 3
    For anyone who's interested, this bug does occur on pg. 236 of Fundamentals of Python: First Programs by Kenneth Lambert, and so wasn't originated by the OP. Commented Aug 9, 2014 at 20:30
  • @DSM, how did you find that? Commented Aug 9, 2014 at 20:32
  • @PadraicCunningham: googled the line of code least likely to have been written by a beginner (the return line.) Commented Aug 9, 2014 at 20:36

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.