Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!In manufacturing, casting is the process of pouring a liquefied or molten metal into a mold, and letting it cool to obtain the desired shape. In programming, casting refers to converting an object of one type into another. Here, we shall learn about type casting in Python.
In Python there are different data types, such as numbers, sequences, mappings etc. There may be a situation where, you have the available data of one type but you want to use it in another form. For example, the user has input a string but you want to use it as a number. Python’s type casting mechanism let you do that.
Implicit Casting in Python
Casting is of two types − implicit and explicit.
When any language compiler/interpreter automatically converts object of one type into other, it is called implicit casting. Python is a strongly typed language. It doesn’t allow automatic type conversion between unrelated data types. For example, a string cannot be converted to any number type. However, an integer can be cast into a float. Other languages such as JavaScript is a weakly typed language, where an integer is coerced into a string for concatenation.
Note that memory requirement of each type is different. For example, an integer object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because of its fractional part. Hence, Python interpreter doesn’t automatically convert a float to int, because it will result in loss of data. On the other hand, int can be easily converted into float by setting its fractional part to 0.
Implicit int to float casting takes place when any arithmetic operation one int and float operands is done.
We have an integer and one float variable
To perform their addition, 10 – the integer object is upgraded to 10.0. It is a float, but equivalent to its earlier numeric value. Now we can perform addition of two floats.
In implicit type casting, the object with lesser byte size is upgraded to match the byte size of other object in the operation. For example, a Boolean object is first upgraded to int and then to float, before the addition with a floating point object. In the following example, we try to add a Boolean object in a float.
Note that True is equal to 1, and False is equal to 0.
Although automatic or implicit casting is limited to int to float conversion, you can use Python’s built-in functions to perform the explicit conversions such as string to integer.
int() Function
Python’s built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer literal representation.
Using int() with an int object as argument is equivalent to declaring an int object directly.
is same as −
If the argument to int() function is a float object or floating point expression, it returns an int object. For example −
The int() function also returns integer 1 if a Boolean object is given as argument.
String to Integer
The int() function returns an integer from a string object, only if it contains a valid integer representation.
However, if the string contains a non-integer representation, Python raises ValueError.
The int() function also returns integer from binary, octal and hexa-decimal string. For this, the function needs a base parameter which must be 2, 8 or 16 respectively. The string should have a valid binary/octal/Hexa-decimal representation.
Binary String to Integer
The string should be made up of 1 and 0 only, and the base should be 2.
The Decimal equivalent of binary number 110011 is 51.
Octal String to Integer
The string should only contain 0 to 7 digits, and the base should be 8.
The Decimal equivalent of octal 20 is 16.
Hexa-Decimal String to Integer
The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F. Base should be 16.
Decimal equivalent of Hexadecimal 2A9 is 681.
You can easily verify these conversions with calculator app in Windows, Ubuntu or Smartphones.
float() Function
float() is a built-in function in Python. It returns a float object if the argument is a float literal, integer or a string with valid floating point representation.
Using float() with an float object as argument is equivalent to declaring a float object directly
is same as −
If the argument to float() function is an integer, the returned value is a floating point with fractional part set to 0.
The float() function returns float object from a string, if the string contains a valid floating point number, otherwise ValueError is raised.
The reason of ValueError here is the presence of comma in the string.
For the purpose of string to float conversion, the sceientific notation of floating point is also considered valid.
str() Function
We saw how a Python obtains integer or float number from corresponding string representation. The str() function works the opposite. It surrounds an integer or a float object with quotes (') to return a str object. The str() function returns the string.
representation of any Python object. In this section, we shall see different examples of str() function in Python.
The str() function has three parameters. First required parameter (or argument) is the object whose string representation we want. Other two operators, encoding and errors, are optional.
We shall execute str() function in Python console to easily verify that the returned object is a string, with the enclosing quotation marks (').
Integer to string
Float to String
str() function converts floating point objects with both the notations of floating point, standard notation with a decimal point separating integer and fractional part, and the scientific notation to string object.
In the second case, a division expression is given as argument to str() function. Note that the expression is evaluated first and then result is converted to string.
Floating points in scientific notations using E or e and with positive or negative power are converted to string with str() function.
When Boolean constant is entered as argument, it is surrounded by (') so that True becomes 'True'. List and Tuple objects can also be given argument to str() function. The resultant string is the list/tuple surrounded by (').
Conversion of Sequence Types
List, Tuple and String are Python’s sequence types. They are ordered or indexed collection of items.
A string and tuple can be converted into a list object by using the list() function. Similarly, the tuple() function converts a string or list to a tuple.
We shall an object each of these three sequence types and study their inter-conversion.
Thus Python’s explicit type casting feature allows conversion of one data type to other with the help of its built-in functions.
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.