Search code examples
pythonidentifier

Python Invalid Character in Identifier


the python code below is getting the error invalid character in identifier. Any idea why? Its an unfinished function I am writing and returned None early as it wasn't running due to this error.

def spotifyrecs(mylibrary, newsongs):
    total = 0
    count = 0
    genredict = {}
    for artist in mylibrary:
        artistsongs = mylibrary[artist]
        for adict in artistsongs:
            total += adict["plays"]
            count += 1
            if adict["genre"] not in genredict:
                genredict[adict["genre"]] = 1
            if adict["genre"] in genredict:
                genredict[adict["genre"]] += 1
    avgplays = round(total / count, 2)
    genrelist = []
    for genre in genredict:
        newtup = (genredict[genre], genre)
        genrelist.append(newtup)
    genrelist.sort(reverse = True)
    return None

library = ​{"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
songs = [{"title": "Loving is Easy", "artist": "Rex Orange County", "plays": 115, "genre": "R&B"}, {"title": "Halo", "artist": "Beyonce", "plays": 9, "genre": "R&B"}, {"title": "Focus", "artist": "Ariana Grande", "plays": 112, "genre": "pop"}, {"title": "Winter", "artist": "Khalid", "plays": 800, "genre": "R&B"}]
print(spotifyrecs(library, songs))

Error:

  File "so.py", line 22
    library = ​{"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
              ^
SyntaxError: invalid character in identifier

Solution

  • You have a non-printing character in your input: get rid of the <200b> character, and this runs nicely.

    library = <200b>{
        "Ariana Grande": [
            {"title": "thank u, next", "plays": 100, "genre": "pop"}, 
            {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}
        ],
        "Khalid":[
            {"title": "Location", "plays": 15, "genre": "R&B"},
            {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}
        ]}
    

    Note that it helps a lot to make your program more readable. Separating this onto individual lines and indenting nicely did two things: (1) the parser gives me a better location, since it can issue the error message at end-of-line; (2) I could look for simple typos and bracket balance much more easily this way.