python 2.2 string conversion ?
gherron at islandtraining.com
Thu Jul 24 08:10:30 CEST 2003
> >>> x="e10ea210"
> >>> y=long(x)
> Traceback (most recent call last):
> File "<pyshell#7>", line 1, in ?
> ValueError: invalid literal for long(): e10ea210
> What am I doing wrong?
You didn't specify what you are trying to do here, but I'll make a
wild *guess* that the string in x is a hexadecimal (i.e., base 16)
value. However, Python can't go around making such a guess, so you
have to explicitly specify your radix (radix being another term for
base) like this:
>>> print long("e10ea210",16)
or tell it to infer the radix from a '0x' prefix:
>>> print long("0xe10ea210",0)
Here are the relevant portions of the manual:
Convert a string or number to a long integer. If the argument is a
string, it must contain a possibly signed number of arbitrary size,
possibly embedded in whitespace; this behaves identical to
string.atol(x). The radix argument is interpreted in the same way as
for int(), and may only be given when x is a string. Otherwise, the
argument may be a plain or long integer or a floating point number,
and a long integer with the same value is returned. Conversion of
floating point numbers to integers truncates (towards zero).
Convert 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;
this behaves identical to string.atoi(x[, radix]). The radix
parameter gives the base for the conversion and may be any integer
in the range [2, 36], or zero. If radix is zero, the proper radix is
guessed based on the contents of string; the interpretation is the
same as for integer literals. If radix is specified and x is not a
string, TypeError is raised. Otherwise, the argument may be a plain
or long integer or a floating point number. Conversion of floating
point numbers to integers truncates (towards zero). If the argument
is outside the integer range a long object will be returned instead.
More information about the Python-list