Where's-the-pi
Where's-the-pi

Reputation: 231

How to check if a number is a number when it is a 'string'?

This is a part of a larger program. Here is what I am trying to do.

  1. Pass a sentence to the scan method.
  2. Have the sentence contain numbers.
  3. Split the sentence into it's different terms.
  4. append to a list a tuple, the first expression in the tuple being the type of thing that the word or sentence element fits into, the second being the word or number.

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

Answers (3)

Ryan Haining
Ryan Haining

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

PaulMcG
PaulMcG

Reputation: 63709

Since you only need positive integers, then try elif word.isdigit(): (note that this will also accept "0").

Upvotes: 5

ConfusedProgrammer
ConfusedProgrammer

Reputation: 616

You could apply int to word and catch a ValueError if it's not a number.

Upvotes: 0

Related Questions