Types casting in Python

Rumman Ansari   Software Engineer   2022-10-08   331 Share
☰ Table of Contents

Table of Content:


Types and casting in Python

Typecasting allows Python programmers to convert an entity from one data type to another. For instance, you may want to convert a string data type such as “2000” to a number type. But why do you need type casting in Python?”

You may want to take advantage of certain properties of a particular object data type. For instance, you may declare a string variable data type that has the operations of “+ and *) as we have learned earlier in our previous section on strings. But you may want to apply number operations such as “/, - and |.” For you achieve numerical operations on such a data type, you have to convert it, or typecast such a variable, to a number.

To cast between the different data types, you must specify the data type name as the function. There are several built-in functions that can help you to convert from one data type to another. Examples of these functions are: 

Syntax

Description

int(x [base])

 It converts the value x to an integer where the base defined is a string or not

long(x [base] )

 It converts the value x to the long integer where the base specified is x a string or not

float(x)

 It converts the value xto floating point number

complex (real [imag])

 It produces a complex number

str(x)

 It converts the object x to string data type

eval(str)

 It evaluates the string and returns the object

tuple(x)

 It converts the value xto a tuple

list(x)

 It converts the value x to a list

set(x)

 It converts the value xto a set

dict(x)

 It converts the value x to a dictionary where x must be a sequence of the (key, value) tuples

chr(x)

 It converts the integer to a character

unichr(x)

 It converts an integer to the Unicode character

ord(x)

 It converts the single character to its integer value

hex(x)

 It converts an integer to a hexadecimal string

oct(x)

 It converts an integer to an octal string

Have a look at the example of the code below. What do you think will be the output?

x = "5000"
y = "2000"
print(x + y)
print( int(x) + int(y) )

Output

50002000
7000

Can you explain why the output is like that? Well, the first statement (print x+y) will display a concatenation of two strings: 5000 and 2000. In the second statement, the x variable has been converted to integer data type. Similarly, the second variable has also been converted to integer data type. Thus, the statement print (x+y) prints the sum of x and y, which is 7000.