What is type conversion in python ?

  • In python type casting functions to directly convert one data type to another which is useful in day-to-day and competitive programming.
  • The types conversion consists of two types, they are implicit conversion and explicit conversion.

 Implicit Conversion

  • In python implicit type conversion data types automatically converts one data type to another without any user involvement.

Sample Code

[pastacode lang=”python” manual=”x%20%3D%2010%C2%A0%0A%0Aprint(%22x%20is%20of%20type%3A%22%2Ctype(x))%C2%A0%C2%A0%0A%0Ay%20%3D%2010.6%0A%0Aprint(%22y%20is%20of%20type%3A%22%2Ctype(y))%0A%0Ax%20%3D%20x%20%2B%20y%0A%0Aprint(x)%0A%0Aprint(%22x%20is%20of%20type%3A%22%2Ctype(x))” message=”” highlight=”” provider=”manual”/]

Output

Explicit Conversion

  • In python explicit conversion data type is manually changed by the user as per their requirement.
    • Int () function convertsany data type to integer. ‘Base’ specifies the base in which string is if the data type is a string.
    • Float () function is used to convert any data type to a floating-point number.
    • Ord () function is used to convert a character to integer.
    • Hex () function is used to convert integer to hexadecimal string.
    • Oct () function is used to convert integer to octal string.
    • Tuple () function is used to convert to a tuple.
    • Set () function returns the type after converting to a set.
    • List () function is used to convert any data type to a list type.
    • Dict () function is used to convert a tuple of order into a dictionary.
    • Str () function is used to convert integer into a string.
    • Complex () function converts real numbers to complex number.
    • Chr () function converts number to its corresponding ASCII character.

Sample Code

[pastacode lang=”python” manual=”%23%20Python%20code%20to%20demonstrate%20Type%20conversion%0A%0A%23%20using%C2%A0%20tuple()%2C%20set()%2C%20list()%0A%0A%23%20initializing%20string%0A%0As%20%3D%20’geeks’%C2%A0%C2%A0%0A%0A%23%20printing%20string%20converting%20to%20tuple%0A%0Ac%20%3D%20tuple(s)%0A%0Aprint%20(%22After%20converting%20string%20to%20tuple%20%3A%20%22%2Cend%3D%22%22)%0A%0Aprint%20(c)%0A%0A%23%20printing%20string%20converting%20to%20set%0A%0Ac%20%3D%20set(s)%0A%0Aprint%20(%22After%20converting%20string%20to%20set%20%3A%20%22%2Cend%3D%22%22)%0A%0Aprint%20(c)%C2%A0%0A%0A%23%20printing%20string%20converting%20to%20list%0A%0Ac%20%3D%20list(s)%0A%0Aprint%20(%22After%20converting%20string%20to%20list%20%3A%20%22%2Cend%3D%22%22)%0A%0Aprint%20(c)” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like