0

I am trying to make a code that converts string into int and doesn't make any errors when the string is letters. My idea is to check if that string is numbers and if it is then it would do something. If it is not, it will print something and will go back to the start of the function. Example:

i = ()
def converter(i):
    i = input()
    if isinstance(i, int) == True:
        print('i is an integer')
    else:
        print('i is not an integer')
        converter(i)
#doesn't work :(

Or something along the lines. The idea is for the program not to crash when a string is typed in and that's why I can't use i = int(input()). Thanks in advance and have a nice day!

3 Answers3

1

I'd approach it more like this:

def converter(your_string):
    try:
        the_integer = int(your_string)
        print(the_integer)
    except ValueError:
        print("Catch Your Error, So Not An Error")
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
0

You can simply use isdigit() to check the integers in string

a=input()
for i in range(len(a)):
    if a[i].isdigit():
        #integer is present
    else:
        #notpresent
Scrapper
  • 182
  • 3
0

You can use a regular expession to filter out non-numeric characters from your string:

>>> import re
>>> re.sub(r"\D", "", "1324l1kj234klj1235")
'132412341235'

Your script could then be

import re

def converter(string):
    return re.sub(r"\D", "", string)

i = input()
print(converter(i))
wvdgoot
  • 303
  • 2
  • 10