Sometimes we need to convert the string into an integer value. In our HTML form, when we submit the form, it takes the value as a string. If we submit a number as a value, then it will be considered as a string value. So it is necessary to convert it to an integer for performing further actions on that value.
We can convert String to Integer using type casting in different languages. Python provides the inbuilt function for converting the string value into an integer value.
The int() function is used for conversion. It returns the integer value for the given string value.
Syntax
Var_name = int(str_value);
Here the string value is given as a parameter to int() function, and it will return the integer value and assigning it to var_name variable.
Example
We have a variable str_val containing string value, and we want to convert it into an int value and assign it to the int_val variable.
It can be done in python as follows:
str_val = ‘200’ int_val = int(str_val) print(int_val)
Explanation
Read Also: How to Copy File in Python
We can also convert the string into an integer with different base values. Usually, python returns value as base 10. But we can convert it to base 8, 16, and 32 according to requirement.
Syntax
base_int_val = int(str_val,base)
Here str_val and base are the parameters for int function. Base specifies in which base you want the integer value, and it will return the integer value and assign it to base_int_val variable.
Example
Suppose we have a value 100 as a string value, and we want to convert it into int value with base eight and sixteen and thirty-two. It can be done by using the below method.
str_val = ‘100’ print(type(str_val)) int_val = int(str_val) print(int_val) int_val_8 = int(str_val, base = 8) print(int_val_8) int_val_16 = int(str_val, base = 16) print(int_val_16) int_val_32 = int(str_val, base = 32) print(int_val_32)
Explanation
This all about converting the string into an integer format. It is used when we get numbers as a string, and we want to perform some mathematical operations on that number.
I hope you found this post informative and helpful.
Thank you for reading 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…