Table of Contents

Python Casting

  • If you want to convert one data type to another data type then python casting is used.
  • In that cases, the different basic function is used in python casting.
    • int() – Using this function returns all data in integer forms, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
    • float() – Using this function returns all  data in floating-point number forms, a float literal or a string literal (providing the string represents a float or an integer)
    • str() – Using this function returns all data in the string(collection of characters knowns as string) forms constructs a string from a wide variety of data types, including strings, integer literals, and float literals
Example

Integer

x = int(2)   # x will be 2
y = int(3.8) # y will be 3
z = int("4") # z will be 4
Example

Floats

x = float(5)     # x will be 5.0
y = float(3.8)   # y will be 3.8
z = float("4")   # z will be 4.0
w = float("6.2") # w will be 6.2
Example

String

x = str("N1") # x will be 'N1'
y = str(6)    # y will be '6'
z = str(4.0)  # z will be '4.0'