Type Conversion

Python Java
Numeric types can be converted to other numeric types by using the appropriate type conversion functions. The function’s name is the name of the destination type. 

Examples:

int(3.14)

float(3)

The ord and chr functions are used to convert between integers and characters, as follows:

ord(‘A’)

chr(65)

The str function converts any Python object to its corresponding string representation.

str(45)

str(3.14)

Numeric types can be converted to other numeric types by using the appropriate cast operators. A cast operator is formed by enclosing the destination type name in parentheses. 

Examples:

(int) 3.14

(double) 3

(char) 45

(int) ‘a’

When casting from an integer to a character or the other way around, the integer is assumed to be the character’s Unicode value.

The simplest way to convert any value to a string is to concatenate it to an empty string, as follows:

“” + 3.14

“” + 45

© Ken Lambert. All rights reserved.