Python Casting

Specify a Variable Type
At some time, there comes any condition where you wwant to specifythe type of any variable and this process is called as casting. As we know that python is an object oriented language, so to define the data types it uses the classes, including it's primitive type.

Therefore in python casting is done using constructor functions:

  • int() - it constructs an integer number from an integer, a float or a string literal. From a float literal it constructs the integer number by rounding down to the previous whole number and from the string literal it constructs an integer number by providing the string represents a whole number.
  • float() -it constructs an float number from an integer, a float or a string literal. From the string literal it providing the string represents a loat or an integer. constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a loat or an integer)
  • str() -it constructs a string from various data types or literals like integer and float literals etc..
  • >>>x=int(2.5)

    >>>print(x,type(x))


    >>>x=str(5)

    >>>print(x,type(x))


    >>>x=float(4)

    >>>print(x,type(x))