Reputation: 231
This is a part of a larger program. Here is what I am trying to do.
Here is what I am trying:
def scan(self, sentence):
self.term = []
for word in sentence.split():
if word in direction:
self.term.append(('direction', word))
elif word in verbs:
self.term.append(('verb', word))
elif word in stop:
self.term.append(('stop', word))
elif word in nouns:
self.term.append(('noun', word))
elif type(int(word)) == 'int':
self.term.append(('number', int(word)))
else:
self.term.append(('error', word))
return self.term
print lexicon.scan('12 1234')
This is a method in a class, the print statement is outside. The part I am concerned with and having trouble with is this:
elif type(int(word)) == int:
self.term.append(('number', int(word)))
It should work for any natural number [1, infinity)
Edit: I run into a problem when I try to scan('ASDFASDFASDF')
Upvotes: 0
Views: 617
Reputation: 36782
if word.lstrip('0').isdigit():
#append
Using the .lstrip('0')
will remove leading 0's and cause strings such as '0'
and '000'
to not pass the check. Simply doing if word.isdigit() and word !='0'
will not exclude '00'
or any other string that is just multiple '0'
s
You could also use a try
/except
/else
to see if it is an int
and respond accordingly
try:
int(s)
except ValueError:
print s, 'is not an int'
else:
print s, 'is an int'
Upvotes: 1
Reputation: 63709
Since you only need positive integers, then try elif word.isdigit():
(note that this will also accept "0").
Upvotes: 5
Reputation: 616
You could apply int
to word
and catch a ValueError
if it's not a number.
Upvotes: 0