I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this.
list = []
i = 0
for row in reader:
list.append([])
list[i].append(row[0])
...
i += 1
I want to check one of these fields to see if it's an number (integer).
When I perform a print type(list[i][0])
it returns a <type 'str'>
even though the value is say 100.
The if statements below are in a for
loop iterating through the lists so what I was thinking of doing is doing a check:
if type(list[i][0] == types.IntType):
True
else:
False
This works, however that's frowned upon in PEP8 and so I should be using isinstance()
, therefore I have modified it to
# check if a value is entered
if list[i][0] != '':
if isinstance(int(list[i][0]), int):
True
else:
False
else
False
But I run into the problem of trying to convert a string to an int (if the user enters a string).
How do I overcome this? It seems like a simple issue however I am new to Python so I was wondering of a neat and efficient way of dealing with this. Should I be checking if the value is an int before storing it into the list?
I am using Python2.
Thanks
edit: I have wrapped the isinstance()
check around a try exception catch however I feel like I shouldn't have to resort to this just to check if something is an int or not? Just curious if there was a neater way to do this.
edit: I have used isdigit
as mentioned previously however I was getting negative results.
i.e. given this data set. list[0][0] = 123, list[1][0] = asdasd
for i in range(0, 1):
if (list[i][0]).isdigit:
tempInt = list[i][0]
print type(tempInt)
print 'True: ' + tempInt
else:
tempInt = 1
print 'False: ' + tempInt
Results:
<type 'str'>
True: 123
<type 'str'>
True: asdasd