Quickie: converting r"\x2019" to int

Frank Millman frank at chagford.com
Fri Apr 7 05:29:47 EDT 2006


Robin Haswell wrote:
>
> rob at aranea:~$ python
> Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
> [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> int("\x2019")
> 19
> >>>
>
> Something like that. Except with:
>
> >>> int(r"\x2019")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): \x2019
> >>>
>
>
> :-)
>
> -Rob

I decided to use this as a learning exercise for myself. This is what I
figured out. All quotes are paraphrased from the docs.

"\xhh in a string substitutes the character with the hex value hh.
Unlike in Standard C, at most two hex digits are accepted."

\x20 is equal to a space. Therefore '\x2019' is equal to ' 19'.

"int(x) converts a string or number to a plain integer. If the argument
is a string, it must contain a possibly signed decimal number
representable as a Python integer, possibly embedded in whitespace."

Therefore int(' 19') is equal to 19.

"When an 'r' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in
the string".

Therefore r'\x2019' is left unchanged, and cannot be converted to an
int.

Rob, this explains *why* you are getting the above error. It does not
explain how to achieve your objective, as you have not specified what
it is. If you give more information, one of the resident gurus may be
able to assist you.

Frank Millman




More information about the Python-list mailing list