Linux/Unix > Python Essential Reference, Second Edition > 4. Operators and Expressions > Type Conversion | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104030195078083247235198

### Type Conversion

Sometimes it’s necessary to perform conversions between the built-in types. The following built-in functions perform explicit type conversions:

Function | Description
--- | ---
`int(``x` `[,``base` `])` | Converts `x` to an integer
`long(``x` `[,``base` `])` | Converts `x` to a long integer
`float(``x` `)` | Converts `x` to a floating-point number
`complex(``real` `[,``imag` `])` | Creates a complex number
`str(``x` `)` | Converts object `x` to a string representation
`repr(``x` `)` | Converts object `x` to an expression string
`eval(``str` `)` | Evaluates a string and returns an object
`tuple(``s` `)` | Converts sequence `s` to a tuple
`list(``s` `)` | Converts sequence `s` to a list
`chr(``x` `)` | Converts an integer to a character
`unichr(``x` `)` | Convert an integer to a Unicode character
`ord(``x` `)` | Converts a single character to its integer value
`hex(``x` `)` | Converts an integer to a hexadecimal string
`oct(``x` `)` | Converts an integer to an octal string

You also can write the `repr(``x` `)` function using backquotes as ````x` ```. Note that the `str()` and `repr()` functions may return different results. `repr()` typically creates an expression string that can be evaluated with `eval()` to re-create the object. On the other hand, `str()` produces a concise or nicely formatted representation of the object (and is used by the `print` statement). The `ord()` function returns the integer ordinal value for a standard or Unicode character. The `chr()` and `unichr()` functions convert integers back into standard or Unicode characters, respectively.

To convert strings back into numbers and other objects, use the `int()`, `long()`, and `float()` functions. The `eval()` function can also convert a string containing a valid expression to an object. For example:

    a = int("34")             # a = 34
    b = long("0xfe76214", 16) # b = 266822164L (0xfe76214L)
    b = float("3.1415926")    # b = 3.1415926
    c = eval("3, 5, 6")       # c = (3,5,6)

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.