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?

Asked By: whoami



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}', '-'))
Answered By: jirassimok

I think you were wrong or badly copied the example, what happens is that the character that looked like it was a negative sign (-) was another character and read it as if it was not that negative sign
Here I leave it corrected.

list(map(abs, [-1, -2, 0, 1, 2]))

Good luck!