Type Casting

  • Type Casting is a method of converting a variable data type into a fixed data type
  • There are two variations of Type Casting followed in Python:
    • Implicit Type Casting
    • Explicit Type Casting

    Implicit Type Casting

    • In implicit type casting, Python automatically converts a data type to another data type
    • Here no inputs are required from user to convert the data type
    X = 123

    Y = 1.23

    Z = x+ y

    print("datatype of X:",type(X)) print("datatype of y:",type(y))

    print("Value of Z:",Z,type(Z))

    Explicit Type Casting

    • Explicit type casting is required to be executed by the user to convert a variable data type into another data type
    • Most commonly used methods:
      • Int()
      • Float()
      • Str()

    Int()

    x = int(1)   # x will be 1
    y = int(2.8) # y will be 2
    z = int("3") # z will be 3

    float()

    x = float(1)     # x will be 1.0
    y = float(2.8)   # y will be 2.8
    z = float("3")   # z will be 3.0
    w = float("4.2") # w will be 4.2

    str()

    x = str("s1") # x will be 's1'
    y = str(2)    # y will be '2'
    z = str(3.0)  # z will be '3.0'

    Other methods

    ord()

    This method accepts any string of length 1 as an argument and returns its unicode point representation.

    hex() : 

    This method converts integer into hexadecimal  string

     hex(56) ->0x38

    oct() : 

    This method converts integer into octal string

    c = oct(56) ->0o70

    chr(number) : 

    This method converts a number into its corresponding ASCII character.

    a = chr(76)  ->L

    Note

    • Data loss can be avoided in Implicit type casting as it is automatically performed by the interpreter where it converts smaller data types into larger data types.
    • In Explicit type Casting, data loss may occur as it is at the discretion of the user to select the new data type for conversion.

    0 Comments

    Leave a Reply

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