Parse String to Int in Python

In order to parse a string to integer use 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:

Parse a string with commas to integer

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

Result:

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

To split 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:

Parse a decimal string to 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 as an integer. You can do it with positive and negative values.

Result: