(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Datatype Conversion
Updated on Jan 07, 2020
Once in a while you will want to convert data type of one type to another type. Data type conversion is also known as Type casting.
Converting int to float #
To convert int
to float
you can use the float()
function.
1 2 3 | >>> i = 10
>>> float(i)
10.0
|
Converting float to int #
To convert float
to int
you need to use int()
function.
1 2 3 | >>> f = 14.66
>>> int(f)
14
|
Converting string to int #
To convert string
to int
, use the int()
function.
1 2 3 | >>> s = "123"
>>> int(s)
123
|
tip:
If string contains non numeric character then int()
will throw ValueError
exception.
Converting number to string #
To convert a number to string use the str()
function.
1 2 3 4 5 6 | >>> i = 100
>>> str(i)
"100"
>>> f = 1.3
str(f)
'1.3'
|
Rounding numbers #
Rounding numbers is done via the round()
function.
Syntax: round(number[, ndigits])
1 2 3 | >>> i = 23.97312
>>> round(i, 2)
23.97
|
Next we will cover control statements.
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments