It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
Answer from Nathan Jones on Stack OverflowIt is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
Safe casting in python - Stack Overflow
Converting a string input to a number or integer
Add a default option to int() to use if conversion fails - Ideas - Discussions on Python.org
i am a beginner at python and im trying to convert string to int but it doesn't work
Videos
Think not, but you may implement your own:
Copydef safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0
I do realize that this is an old post, but this might be helpful to some one.
Copyx = int(word) if word.isdigit() else None
Hello Everyone,
I was wondering if it's possible to get the input of a string from the user and convert it into an integer later on. I'm asking this as the code I'm working on requires a string input from the user of what service they'd like. I later had to add up the totals of the services and wondered if once the choice was selected or inputted then if it would become a number that later adds up to the total cost if multiple services are inputted.