Probably a stupid newbie question....i got to ask
David Bolen
db3l at fitlinxx.com
Wed Aug 8 22:36:44 EDT 2001
fett at tradersdata.com writes:
> How do you use string.atoi to convert a variable integer to a string?
You don't, because string.atoi does the reverse - converts a string
into an integer. (The "atoi" is for alpha/ascii to integer)
The function documentation spells this out:
>>> print string.atoi.__doc__
atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
Thus, for example:
>>> string.atoi('10')
10
>>> string.atoi('152')
152
>>> string.atoi('-5')
-5
>>> string.atoi('0xA',16)
10
and it only works on integers (use string.atof for float):
>>> string.atoi("-152.0")
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for atoi(): -152.0
If you want to go the other way (convert an integer into a string),
you have a few alternatives:
* Use str(###) - this is the simplest way to get a printable string
representation of any object.
>>> str(10)
'10'
* Use a format string. String formatting can use %s to perform
the same operation as str(), or formats such as %d for integers or
%f for floating point.
>>> '%s' % 10
'10'
>>> '%d' % 10
'10'
>>> '%5d' % 10
' 10'
>>> '%5.2f' % 10
'10.00'
You can also use %x/%X (hex) or %o (octal) in format strings to
perform a base conversion.
>>> '%o' % 10
'12'
>>> '%x' % 10
'a'
>>> '%X' % 10
'A'
--
-- David
--
/-----------------------------------------------------------------------\
\ David Bolen \ E-mail: db3l at fitlinxx.com /
| FitLinxx, Inc. \ Phone: (203) 708-5192 |
/ 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \
\-----------------------------------------------------------------------/
More information about the Python-list
mailing list