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.
>Solution :
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.