I have a text files that I read to a list. This list contains integers and strings.
For example, my list could look like this:
[\"name\", \"test\", \"1\"
Try it, and catch the exception if it fails:
try:
return int(obj)
except ValueError:
...
Python takes the view of it's easier to ask for forgiveness than permission. Looking before you leap is often slower, harder to read, and can often introduce race conditions (not in this instance, but in general).
Also, modifying a list in-place like that is a bad idea, as accessing by index in Python is slow. Instead, consider using a list comprehension like this:
def intify(obj):
try:
return int(obj)
except ValueError:
return obj
mylist_with_ints = [intify(obj) for obj in mylist]
This makes a new list with the modified values and is more readable and efficient.
As a note, as we are just applying a function to every item of a list, map()
would also work well here:
mylist_with_ints = map(intify, mylist)
Note that if you need a list instead of an iterable in 3.x, you will want to wrap the map call in list()
.
The way to convert to integers is to try the conversion and be prepared for it to fail:
for i in range(len(mylist)):
try:
mylist[i] = int(mylist[i])
except ValueError:
pass
The method tests for digits only, and -
is not a digit. You need to test with int()
and catch the ValueError
exception instead if you wanted to detect integers:
for i, value in enumerate(mylist):
try:
mylist[i] = int(value)
except ValueError:
pass # not an integer
In other words, there is no need to test explicitly; just convert and catch the exception. Ask forgiveness rather than ask for permission.