0

I'm trying to remove vowels from a string. Specifically, remove vowels from words that have more than 4 letters.

Here's my thought process:

(1) First, split the string into an array.

(2) Then, loop through the array and identify words that are more than 4 letters.

(3) Third, replace vowels with "".

(4) Lastly, join the array back into a string.

Problem: I don't think the code is looping through the array. Can anyone find a solution?

def abbreviate_sentence(sent):

    split_string = sent.split()
    for word in split_string:
        if len(word) > 4:
            abbrev = word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
            sentence = " ".join(abbrev)
            return sentence


print(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"
peyo
  • 351
  • 4
  • 15
  • 1
    Possible duplicate of [Find and replace string values in list](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-list) – peyo Sep 22 '19 at 04:33

1 Answers1

0

I just figured out that the "abbrev = words.replace..." line was incomplete.

I changed it to:

abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") if len(words) > 4 else words for words in split_string]

I found the part of the solution here: Find and replace string values in list.

It is called a List Comprehension.

I also found List Comprehension with If Statement

The new lines of code look like:

def abbreviate_sentence(sent):

    split_string = sent.split()
    for words in split_string:
        abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
                        if len(words) > 4 else words for words in split_string]
        sentence = " ".join(abbrev)
        return sentence


print(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"
peyo
  • 351
  • 4
  • 15