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.

It can be done by 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:**

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

1 2 3 |
str_val = ‘200’ int_val = int(str_val) print(int_val) |

**Explanation:**

- First, we assign the string value 200 to the str_val variable.
- Then we use the int() function for converting the string to an int value.
- Then after we assign it to the int_val variable.
- Finally, we print the int value.

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

1 |
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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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:**

- First, we assign the 100 as a string value to variable str_val.
- Next, we convert it into an integer value and assign it int_val variable.
- After that, we convert str_val into an integer value with base eight and assign it to the int_val_8 variable.
- Then, we convert str_val into an integer value with base sixteen and assign it to the int_val_16 variable.
- Finally, we convert str_val into an integer value with base thirty-two and assign it to the int_val_32 variable.

**Conclusion**

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 🙂