Monday, 29 May 2023

Convert a string to integer in Python

Using int() function, you can convert a string to an integer in Python.

 

Example

int_var = int(input_str)

 

string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

int_var = int(input_str)
print('int_var : ', int_var, " type : ", type(int_var))

Output

Enter a string 12345
input_str :  12345  type :  <class 'str'>
int_var :  12345  type :  <class 'int'>

If the input_str contains any non-numeric characters, you will endup in ValueError like below.

Enter a string hello
input_str :  hello  type :  <class 'str'>
Traceback (most recent call last):
  File "/Users/Shared/PycharmProjects/python/python-core/1.introduction/string_to_int.py", line 4, in <module>
    int_var = int(input_str)
ValueError: invalid literal for int() with base 10: 'hello'

We can handle above error situations using try-except block.

 


string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

try:
    int_var = int(input_str)
    print('int_var : ', int_var, " type : ", type(int_var))
except ValueError as ve:
    print("input string contain non numeric characters. error : ", ve)

Output

Enter a string hello
input_str :  hello  type :  <class 'str'>
input string contain non numeric characters. error :  invalid literal for int() with base 10: 'hello'




Previous                                                 Next                                                 Home

No comments:

Post a Comment