Datatype casting

Python determines the datatype automatically, to illustrate:

x = 3
y = "text"

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.

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
y = 2.15315315313532
print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

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"
b = "133.1112223"
c = float(a) + float(b)

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

16 thoughts on “Datatype casting

  1. Hh - November 7, 2015

    Thank you

  2. Bruno - August 4, 2015

    In print “x = ” + str(x) couldn’t we replace the “+” for a comma?

    1. Frank - August 4, 2015

      Hi Bruno, thanks for your comment! This outputs the same but does not concatenate the string data. If you only want to ouput, this is fine. If you want to do operations on the string later, you can store the output in a string value that way.

  3. Mason - July 9, 2015

    In the paragraph: An example of casting datatypes in Python:

    There is a typo in the sentence “In this example below we weant to print”

    I really like this tutorial thanks for making it!

    1. Frank - July 9, 2015

      Thanks Mason! I updated it