-1

I have a function that takes a string as its input. The string can contain Integer numbers as well. I want to remove the spaces between the words and any integer that is greater than, for example, 5. How can I do this?

def my(str):
    x = [i for i in str]
    for items in x:
        if items == ' ':
            x.remove(items)
    new_items = [x for x in x if not x.isdigit()]
    return(new_items)

print(my('7 monkeys and 1 tiger'))

So far I have tried this. It removes both 7 and 1 from the string. Here is the output:

['m', 'o', 'n', 'k', 'e', 'y', 's', 'a', 'n', 'd', 't', 'i', 'g', 'e', 'r']

But I wanted to remove only 7 but not 1.

Rifly
  • 33
  • 1
  • 8
  • 1
    `if not x.isdigit() or x.isdigit() and int(x) < 5`. Note that your code only checks digits one by one. What do you want to happen if the sentence is `"11 monkeys"`? – Guimoute May 16 '22 at 16:13
  • 1
    Your code is mutating the list it is iterating over. Don't do that, because it's difficult to reason about what's happening. Instead, start with an empty result list, and append to it the items you want to keep, instead of removing the ones you don't want to keep. – BoarGules May 16 '22 at 16:14
  • `"".join([word for word in phrase.split(' ') if not word.isdigit() or word.isdigit() and int(word) <= 5])` – 3nws May 16 '22 at 16:16

2 Answers2

1

You can add all the requirements into a single list comprehension:

p = [x for x in '7 monkeys and 1 tiger' if ((not x.isdigit() and not x ==' ') or (x.isdigit() and int(x) < 5))]
print(p)

There are two choices, the index is a digit and less than 5: (x.isdigit() and int(x) < 5) or the index is not a digit and not a space either: (not x.isdigit() and not x ==' ').

Output: ['m', 'o', 'n', 'k', 'e', 'y', 's', 'a', 'n', 'd', '1', 't', 'i', 'g', 'e', 'r']

Or you can use print("".join(p)) to get a single string: monkeysand1tiger.

Jhanzaib Humayun
  • 1,193
  • 1
  • 4
  • 10
0

You can start by splitting the string. That effectively gets rid of the spaces. Then you check each token to see if it's an integer and compare against some constant to determine if it should be included or excluded from the result. Something like this:

def my(s, m=5):
    return ''.join(t for t in s.split() if not (t.isdigit() and int(t) > m))

print(my('7 monkeys and 1 tiger'))

Output:

monkeysand1tiger
DarkKnight
  • 19,739
  • 3
  • 6
  • 22