Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using non-ASCII characters as variable names in Python 2

The following code returns “Error: Invalid Syntax” when reaching the third line:

# -*- coding: utf-8 -*-
print “åäö”
ÅÄÖ = 4

The print statement works fine despite holding non-ASCII characters. The problem seems to be when the non-ASCII characters are used as variable names. Doing this in Python 3 works perfectly fine, and I’ve understood that this is because Python 3 and 2 treat strings differently, but I need to use Python 2 for various reasons.

Being able to write the letters åäö in Python 2.7 would be extremely valuable to me, partly because I am fairly new to programming in Python and strongly prefer naming my variables and functions in Swedish as it makes them much easier to separate from Pythons in-built functions.

like image 583
gelbrekt Avatar asked Nov 02 '25 00:11

gelbrekt


1 Answers

You can't do this. The language syntax specification simply doesn't allow it for Python 2.x:

https://docs.python.org/2/reference/lexical_analysis.html#identifiers

As you already discovered this was changed for Python 3 where the syntax allows certain kinds of non-ascii characters to occur in identifiers

https://docs.python.org/3/reference/lexical_analysis.html#identifiers

(Note that identifiers are something else entirely as string literals!)

like image 63
Irmen de Jong Avatar answered Nov 03 '25 14:11

Irmen de Jong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!