Python Casting

Python Casting


Specify a Variable Type

Sometimes a variable type is required to be specified. Casting can be done this. Python is language oriented to objects, and therefore uses classes to define data types, including primitive types.

Casting in python is therefore done using functions of constructors :

  • int() - an integer number can be constructed from either an int literal, or a float literal (by deleting all decimals) (providing the string represents a whole number).
  • float() - generates a float number from an integer, float or string literal (providing the string represents a float or an integer).
  • str() - allows you to build strings out of strings, integer literals and float literals among other data types.

Example 1 :- Convert to integers

x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)

Output :-

1
2
3




Example 2 :- Convert to floats

x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)

Output :-

1.0
2.8
3.0
4.2

Example 3 :- Convert to strings

x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)

Output :-

s1
2
3.0



You can also search for these topics, how to specify a variable type in python, python is known as specify variable type, python specify the type of a variable, how to assign casting variable type in python, python casting declare variable type list, determine a variable type in python casting, python define member variable type using python casting.