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!

2
  • 1
    Just use a try and except value error.. it's literally it's purpose Commented Apr 14, 2021 at 8:34
  • i = input() means i will always be a str object, and isinstance(i, int) will always be False Commented Apr 14, 2021 at 8:40

3 Answers 3

2

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")
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

you can just use a.isdigit()
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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.