How to do special encode in string ?

Troels Therkelsen t_therkelsen at
Wed Jun 23 15:23:38 CEST 2004

In article <mailman.37.1087982922.27577.python-list at>, fowlertrainer at wrote:
> Hi !
> I'm hungarian, we use special characters like:
> á - a'
> õ -o"
> etc.
> I want to encode this characters to in config file I see these
> characters as \nnn format.
> And I want to decode it automatically with python.
> How to I do it without write complex converter tool ?
> Thanx for it:
> FT
> Example:
> Encode("az állam én vagyok") -> "az \xe1llam \xe9n vagyok"
> Decode("az \xe1llam \xe9n vagyok") -> "az állam én vagyok"

The easiest way is probably just to use repr/eval, like this:

Python 2.3.4 (#1, Jun  4 2004, 19:45:32)
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> repr("az állam én vagyok")
"'az \\xe1llam \\xe9n vagyok'"
>>> print repr("az állam én vagyok")
'az \xe1llam \xe9n vagyok'
>>> eval("'az \\xe1llam \\xe9n vagyok'")
'az \xe1llam \xe9n vagyok'
>>> print eval("'az \\xe1llam \\xe9n vagyok'")
az állam én vagyok

Not that repr() puts a set of '' around the string and eval() needs these in
order to 'parse' the string.

Hope this helps!


Troels Therkelsen

More information about the Python-list mailing list