0

The problem consists of a list of strings where each string has two elements and can be either a letter or a number, we want to create a function that takes this list as a parameter/argument and delete all those strings that have a number in it, I tried this code down below but it does not work.

def erase(lista):
    for word in lista:
        for letter in range (len(word)):
            if letter in [1234567890]:
                del word


erase(["a3", "b3", "aa"])
halfer
  • 19,824
  • 17
  • 99
  • 186
fabr0
  • 3
  • 1
  • 5
    Welcome to Stack Overflow. What does "it does not work" mean, specifically? Do you get error messages? What do they say? Does it just do something unexpected? What do you expect, and what happens instead? Please read [ask]. – ChrisGPT was on strike Feb 02 '20 at 22:21
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – ChrisGPT was on strike Feb 02 '20 at 22:23
  • Hi! Thanks for answering that fast, actually it does not recognize whether each letter is in the number array or not so the word cant be erased, do you know how this problem could be solved?, Thanks! – fabr0 Feb 02 '20 at 22:25
  • 1
    That is because your line `if letter in [1234567890]:` is completely wrong. First of all the vaiable `letter` does not actually hold a letter - it is ints from the `range(len(word))`. You probably meant `for letter in word`. Second you are basically checking if that letter/number is equal to `1234567890`. Again, you probably meant `if letter.isdigit()` – Tomerikoo Feb 02 '20 at 22:34
  • fabr0, please add your specific question into the question, so as to make it on-topic. Thanks! – halfer Feb 05 '20 at 18:52

1 Answers1

0

If you want to check if a char is a number, you can use isdigit function

my_list = ["a3", "b3", "aa"]

def erase(lista):
    only_chars = []
    for word in lista:
        result = ''.join([w for w in word if not w.isdigit()])
        if result:
            only_chars.append(result)

    return only_chars


result = erase(my_list)
print(result)

it will print:

['a', 'b', 'aa']

If you want to remove all string that contains numbers, you can use isdigit combined with any:

my_list = ["a3", "b3", "aa"]

def erase(lista):
    only_chars = []
    for word in lista:
        if not any(w.isdigit() for w in word):
            only_chars.append(word)

    return only_chars


result = erase(my_list)
print(result)

And now, the result is:

['aa']
Rafael Marques
  • 1,501
  • 15
  • 23