Python Forum

Full Version: remove vowels in word with conditional
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(May-01-2021, 06:04 PM)supuflounder Wrote: [ -> ]Don't you mean "<= 4" in line 5?

The problem is that you are doing
shorter = words[index].replace(x, "")
So let's look at what happens

Let words[index] be the string "I don't want any lower-case vowels".
The first time through the loop starting on line 15, your first match is the "o" in "don't". So shorter is set to
"I dn't want any lower-case vowels"
The next time there is a match it matches the a in want, so shorter is set to
"I don't wnt any lower-case vowels"
Do you see the problem?

What you want to do is always test shorter, not words[index]. Which is a bit tricky, because you have removed the letter, so you have to manage the range. I'm not going to write the code for your homework, but this is as much help as I will give.

Thank you for your explanation on what words[index] is doing. It makes sense to me now.
This is not for a homework. I am working on a script for using at work so shorten some element naming. Very new to Python so trying my best to learn as I go with new challenges.
For a limited grammar you may get better results using straight substitution. Create a dictionary mapping your common words to their preferred abbreviation.
I would split string to words and process word with function. For replacement I would use str.translate. Assuming that this is text in english:

import string

s = "Masonry - Concrete Block (Small) - Misc Air Layer - Insulation - Aluminium"
        
def process(word):
    mapping = str.maketrans(dict.fromkeys('aeiou', ''))
    length = 0
    for char in word:
        if char in string.ascii_letters:
            length += 1
            if 4 < length:
                return word.translate(mapping)
    else:    # no-break
        return word

print(' '.join(process(word) for word in s.split()))

# -> Msnry - Cncrt Blck (Smll) - Misc Air Lyr - Insltn - Almnm
Pages: 1 2