Type Casting...

Chris Barker chrishbarker at home.net
Tue Sep 18 15:01:20 EDT 2001


David In VA wrote:
> I have a variable that is storing a numeric value.  I need the string
> representation of that value.  I would imagine type casting would be the
> thing to use.  can someone please tell me how to do this in Python?

Typecasting as such doesn't really exist in Python, however there are
various functions that will change one type to another (int(),
float(),long(), tuple(), etc.).

As for converting numbers to strings, there are many options:

>>> x = 123.45
>>> str(x) # turn this object to a string that is nice to look at.
'123.45'
>>> `x` # these are back quotes, usually on the upper left of your keyboard, they just calls repr()
'123.45'
>>> repr(x) # represent this object as a string, such that eval(repr(x)) == x
'123.45'
>>> "%g"%x # insert these numbers in a string using the format specifiers (similar to sprintf)
'123.45'
>>>

Look in the library reference, and other docs for more detailed
explainations.

-Chris




-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list