S
S
sasha3002018-09-21 12:58:26
Python
sasha300, 2018-09-21 12:58:26

How to remove all words starting with the letter "m" from a string?

Hello!
For 2 days now I can not win the task:
# A line from a poem is given:
# Remove from the line all words starting with the letter "m".
# Print the result to the screen as a string.
# Hint: remember to modify lists.

a = "Мой дядя самых честных правил, Когда не в шутку занемог, \
    Он уважать себя заставил И лучше выдумать не мог"
a = a.split()
for i in range(len(a)): # 0,19
    if a[i][0] == "М" or a[i][0] == "м":
        del a[i]

What gives:
IndexError: list index out of range

It is possible like this:
a = "Мой дядя самых честных правил, Когда не в шутку занемог, \
    Он уважать себя заставил И лучше выдумать не мог"
a = a.split()
for i in range(len(a) - 1): # 0,19
    if a[i][0] == "М" or a[i][0] == "м":
        del a[i]

And the code will successfully remove the first word, but where is the guarantee that the other list will not contain a couple of words starting with the letter "m"? Then you need to put range(len(a) - 2) and so on. My script has a flaw in this.
In short, I see that I have reached a dead end, im need help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2018-09-21
@sasha300

Regular season:

import re
p = re.compile(r"\bм.*?\b", re.I)  # \b — это граница слова, есичё
re.sub(p, "" , s)

Lists:
Correctly:
" ".join(x for x in s.split() if not x.startswith(("м", "М")))

E
Eugene, 2018-09-21
@Eugen_p

Why don't you want to create a new list?

a = "Мой дядя самых честных правил, Когда не в шутку занемог, \
    Он уважать себя заставил И лучше выдумать не мог"
res = [i for i in a.lower().split() if not i.startswith('м')]

If you need to delete it:
a = "Мой дядя самых честных правил, Когда не в шутку занемог, \
    Он уважать себя заставил И лучше выдумать не мог"
a = a.lower().split()
i = 0
while i < len(a):
  if a[i].startswith('м'):
    del a[i]
    continue
  i += 1

V
Vadim Shatalov, 2018-09-21
@netpastor

result = ' '.join(filter(lambda w: w[0] not in ["М", "м"], a.split()))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question