Convert String to Int in Python

In order to parse a string to an integer using the int() function.

Parse a string to int with exception handling

If you want to safely convert a string to INT you have to handle exceptions. If a string cannot be converted to int, the function will return a default value.

This example will illustrate that.

It will return the following result:

123
asd123 value is not an integer

Parse a string with commas to an integer

Sometimes a value is separated by commas. In order to convert this value use the replace() function.

Result:

1500000

Split a string, parse to int, and add to an array [list]

To split a string we can use the split() function. It will separate values and add them to the list as strings. Then we will use map(). This function applies an operation to each element. In this example, it will convert a string to an integer.

Result:

100
23
41
2

Parse a decimal string to an integer and round it up

In order to round up a value that is a string, we need to parse it to a float and then use math.ceil to round it up and return it as an integer. You can do it with positive and negative values.

Result:

The 9.23 rounded up is 10
The -9.23 rounded up is -9