Convert a string into integer or float using Python

featured Image

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 Articles:

Split String and get the first element using python

Split string by whitespace in python

Replace character in String by index in Python

Python – Check if a string is Empty or Not

Python – Remove Newline From Strings (3 Ways)

How to Append String in Python

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *