Convert a string into integer or float using Python
Find out how to convert a string into an integer or floating point number using int() and float() function in Python.
In this short article, we will see how to convert a string value into an integer in python.
To convert any string value into an integer we can use the in-built int() function in python. It can convert any specific value into an integer number.
Syntax:
int(value,base)
value: the value that will be converted to an integer.
base: it represents the number format
Now, let's see an example, of how the int() function is used to convert any value into an integer number.
Convert to interger number using int() function
Example:
num = '124' print(type(num)) // <class 'str'>
Here, we have just checked the data type of the variable num using type() and as you can see it's a string value.
The
type()function returns the data-type of the objects/data in python.
Now, to convert it into an integer number we will use the int() function.
num = '123' converted_num = int(num) print(type(converted_num) // <class 'int'>
Now, when we pass the string value (ie. num variable) in the int() function, it converts and returns an integer value.
Convert a decimal string to int using float() in python
Now, if the number is a decimal number (floating point) then we have to use the float() function.
Example:
num = '10.5' converted_num = float(num) print(type(converted_num)) // <class 'float'>
So to convert a decimal number string in python we have to use the in-built float() function.
Related Posts
How to merge JSON files in python
Learn different techniques to merge multiple JSON files in Python using built-in JSON module and Pandas library. Includes examples for combining data arrays and merging dictionaries by key.
Pytube Description and Keyword Not Showing: Solution
Solve the issue with Pytube not showing youtube description and tags in this article.
How to Fix the subprocess-exited-with-error in Python
Learn what cause the subprocess-exited-with-error in Python and also learn how to solve the error in your code.
Python Integer Division: The Floor Division Operator Explained
Article on Python Integer Division operator (//) with examples and the difference between standard division and floor division.
