Search code examples
pythondictionarycharacteridentifier

Issue in character identifier for abs() in map() Python


Here the only one problem:

list(map(abs, [−1, −2, 0, 1, 2]))
                ^
invalid character in identifier

abs should do it in right way, but map had a problem. So, how to solve this problem?


Solution

  • You've got the Unicode minus sign ("−"; U+2212) instead of the hyphen-minus ("-"; U+002D) that Python (and most other programming languages) recognize.

    Just replace the minus signs with regular dashes, and the problem should go away.

    If you need to do this across a large amount of data that you're copying from elsewhere, a simple string replacement (similar to the solution in this answer) before you parse the data should do the job:

    with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
        for line in infile:
            outfile.write(line.replace('\N{MINUS SIGN}', '-'))