Friday 24 September 2021

Python: Convert string to integer

‘class int(x, base=10)’ return an integer object constructed from a number or string x, or return 0 if no arguments are given.

 

convert_string_to_int.py

def get_int(input_str):
    try:
        return int(input_str)
    except ValueError:
        print('Input is not a valid integer')

res1 = get_int('1234')
print('res1 -> ', res1, '\n')

res2 = get_int('56aa78')
print('res2 -> ', res2)

 

Output

res1 ->  1234 

Input is not a valid integer
res2 ->  None

 

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment