Parse String to Int in Python

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

int_value = int('111')

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.

def parse_string_to_int(s):
    try:
        value = int(s)
    except ValueError:
        value = s + ' value is not an integer'
    return value

print(parse_string_to_int('123'))
print(parse_string_to_int('asd123'))

It will return the following result:

123
asd123 value is not an integer

Parse a string with commas to integer

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

str_value = '1,500,000'
int_value = int(str_value.replace(',', ''))
print(int_value)

Result:

1500000

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.

str_value = "100-23-41-2"
str_list = str_value.split('-')

int_list = list(map(int, str_list))

for int_elem in int_list:
    print(int_elem)

Result:

100
23
41
2

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.

import math

str_value1 = "9.23"
str_value2 = "-9.23"

roundup_int1 = math.ceil(float(str_value1))
roundup_int2 = math.ceil(float(str_value2))

print('The ' + str_value1 + ' rounded up is ' + str(roundup_int1))
print('The ' + str_value2 + ' rounded up is ' + str(roundup_int2))

Result:

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