Search code examples
pythontypeerror

TypeError (can't concatenate NoneType to str)


def emoji_convert(massage):
    split_words = massage.split(" ")
    emoji = {
        ":)": " 😁",
        ":(": " 😞",
        ":": " 😶",
        ":|": " 😐"
    }
    output = ""
    for words in split_words:
        output += emoji.get(words)
    return output


massage=(input("> "))
print(emoji_convert(massage))

get this type error

    output += emoji.get(words)
TypeError: can only concatenate str (not "NoneType") to str

Solution

  • The quickest fix is to change the default when emoji doesn't have a match from None to instead an empty string:

    output += emoji.get(words, '')
    

    ...or, to pass the word through unmodified (but for a leading space) when it isn't found:

    output += emoji.get(words, ' ' + words)
    

    You might also consider generating your output as a list, and converting that list to a string right before returning it, thus more properly mirroring the split() you did earlier.

    def emoji_convert(message):
        split_words = message.split(" ")
        emoji = {
            ":)": "😁",
            ":(": "😞",
            ":":  "😶",
            ":|": "😐",
        }
        output = []
        for word in split_words:
            output.append(emoji.get(word), word)
        return ' '.join(output)
    
    message = input("> ")
    print(emoji_convert(message))