Home > Back-end >  Why does the .isdigit() function return an error when I use it?
Why does the .isdigit() function return an error when I use it?

Time:10-11

I am trying to create a function that returns string numbers as "NUM" when the sentence is passed through my function, but I get an error. My code is as follows:

def number_normalise(sentence):
  for token in sentence:
    if sentence[token].isdigit():  # This is the part that returns the error.
      sentence[token] = "NUM"
    else:
      sentence[token]

  return sentence

For the third line of code I get an error saying that "list indices must be integers or slices, not str". I've tested the function separately and it should return a boolean number when it meets a word that is only a number (e.g. "5", "1802"). Could somebody help me understand what is wrong with my code and how I can improve it?

CodePudding user response:

sentence is a list of strings and you are iterating over those strings. So, on line 3 you are actually trying to get a specific element from your list. But instead of integer i.e. sentence[2] you are passing a string i.e. sentence["apple"] which is wrong for obvious reasons.

I think you want to do:

def number_normalise(sentence: List[str]):
    for i, token in enumerate(sentence):
      if token.isdigit():  
         sentence[i] = "NUM"

    return sentence

CodePudding user response:

I don't know what sentence variable is but I think you should write

...
if token.isdigit():
...

CodePudding user response:

I think it's the sentence[token] which is causing problem. token is probably a string while you should ask for the index of the element in sentence

  • Related