How can I check if a string represents an int, without using try/except?
If you're really just annoyed at using try/except
s all over the place, please just write a helper function:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.
Why am I unable to use try-except to convert str to int?
I often use a function to safely convert a string to an int or a float, e.g. to_int
below.
The code below creates an answer Label that's used as required. The original code created a label for every click of the button.
from tkinter import *
def to_int(string, fail = 0):
try:
return int(string)
except ValueError:
return fail
x = {"A": 0.8, "B": 2.5, "C": 1.2}
def p(y):
root = Tk()
root.title("Average Waiting Time")
root.geometry("800x500")
Label(root, text="Enter number of people: ").place(x=20, y=30)
Q = Entry(root, bd =5)
Q.place(x=220, y=30)
answer = StringVar()
answer.set("")
Label(root, textvariable = answer ).place(x=50, y=500)
def B():
Q_input = Q.get()
v = to_int(Q_input, -1)
# Returning <0 triggers the error message
if v <=0 or v > 10:
answer.set("Enter a value from 0 to 10")
else:
W = str(round(v * x[y], 1)) # Round off to 1 d.p
answer.set("Ans\n" + W + " minute(s)")
print(answer.get())
ok = Button (root, text="OK", command = B)
ok.place(x=300, y=300)
cancel = Button (root, text="Cancel", command = root.destroy)
cancel.place(x=400,y=300)
root.mainloop()
Exception Handling, function attempting to convert a string into an integer
def string2int(sti):
try:
return int(sti)
except ValueError:
raise SyntaxError('not an integer')
Or:
def string2int(sti):
if sti.isdigit():
return int(sti)
else:
raise SyntaxError('not an integer')
Trying to convert to numbers with try except
try-except
is for catching exceptions. In this scenario, you only account for one exception, ValueError
but not TypeError
. In order to catch type error, just put one more except
block below try
. In your case, it would be like this:
L = ["29.3", "tea", "1", None, 3.14]
D = []
for item in L:
try:
float(item)
D.append(float(item))
except TypeError:
# do something with None here
except ValueError:
D.append(item)
print(D)
Given that you want to catch multiple exceptions in a single except
block, use a tuple of exceptions:
L = ["29.3", "tea", "1", None, 3.14]
D = []
for item in L:
try:
float(item)
D.append(float(item))
except (ValueError, TypeError):
D.append(item)
print(D)
Is there a built-in or more Pythonic way to try to parse a string to an integer
This is a pretty regular scenario so I've written an "ignore_exception" decorator that works for all kinds of functions which throw exceptions instead of failing gracefully:
def ignore_exception(IgnoreException=Exception,DefaultVal=None):
""" Decorator for ignoring exception from a function
e.g. @ignore_exception(DivideByZero)
e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
"""
def dec(function):
def _dec(*args, **kwargs):
try:
return function(*args, **kwargs)
except IgnoreException:
return DefaultVal
return _dec
return dec
Usage in your case:
sint = ignore_exception(ValueError)(int)
print sint("Hello World") # prints none
print sint("1340") # prints 1340
Try Except String vs Int Python
this solution counts on the fact that int("1.235")
will raise a value error as for a string to convert it must be a literal int. This requires my_value
to be a string! as int(1.235)
will simply truncate the float to an int
my_value = raw_input("Enter Value")
try:
my_value = int(my_value)
except ValueError:
try:
float(my_value)
print "Its a float not an int!"
raise ValueError("Expected Int, got Float!")
except ValueError:
print "Its a string not a float or int"
raise TypeError("Expected Int, got String!")
else:
print "OK its an int"
Related Topics
Get Lat/Long Given Current Point, Distance and Bearing
Find First Element in a Sequence That Matches a Predicate
Python Nested Functions Variable Scoping
What Is the Point of Indexing in Pandas
How to Apply Piecewise Linear Fit in Python
Binary Representation of Float in Python (Bits Not Hex)
Is the Server Bundled with Flask Safe to Use in Production
Underscore _ as Variable Name in Python
How to Add an Integer to Each Element in a List
How to Do/Workaround a Conditional Join in Python Pandas
Python: Can Executable Zip Files Include Data Files
Importerror: No Module Named _Ssl