Tag: casting
python cast
Python determines the datatype automatically, to illustrate:
|
It finds x is of type integer and y of type string.
Functions accept a certain datatype. For example, print only accepts the string datatype.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Datatypes casting
If you want to print numbers you will often need casting.
In this example below we want to print two numbers, one whole number (integer) and one floating point number.
x = 3 |
We cast the variable x (integer) and the variable y (float) to a string using the str() function.
What if we have text that we want to store as number? We will have to cast again.
a = "135.31421" |
In the example above we cast two variables with the datatype string to the datatype float.
Conversion functions
To convert between datatypes you can use:
Function | Description |
---|---|
int(x) | Converts x to an integer |
long(x) | Converts x to a long integer |
float(x) | Converts x to a floating point number |
str(x) | Converts x to an string. x can be of the type float. integer or long. |
hex(x) | Converts x integer to a hexadecimal string |
chr(x) | Converts x integer to a character |
ord(x) | Converts character x to an integer |