Tutorials  Articles  Notifications  Login  Signup


DG

Dhirendra Gupta

Student at BIT Mesra Aug. 4, 2020, 6:19 p.m. ⋅ 1069 views

Type casting in Python


There might be times when we want a variable to be certain type. It usually happens when we need to assign value of one variable to another variable and both are not of same type.

To cast type of any variable in python we can use constructor functions of type of our choice.

  • int() - This gives integer type value after casting the value we pass to it. If we give it a float type variable it will round it down to previous integer value.
>>> int(5.8)
5

If we give it a string value, it will cast to integer value and give value equivalent to its whole number representation. 

>>> int("132")
132
  •  float() - This gives a float type variable of whatever we pass to it.
>>> float(213)
213.0
>>> float("13")
13.0
>>> float("14.9")
14.9
  • str()  - It returns a string type variable from several types of variables.
>>> str("Hello HackersFriend")
'Hello HackersFriend'
>>> str(12321)
'12321'
>>> str(24.9)
'24.9'
>>>

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account