0

The code excludes vowels from a string. The code works, and print() does the job, but I need to return the result. I tried .join() but it didn't work: it returns only the first character in my case, because the return stops the loop. How can I overcome this?

def remove_vowels(document: str) -> str:    
    vowels = "aeioyu"  
    document = document.lower()
    for chart in document:
    if  chart not in vowels:
        print(''.join(chart), end = '' )
        return (''.join(chart))     
remove_vowels("document")   
philipxy
  • 14,867
  • 6
  • 39
  • 83
avkpol
  • 53
  • 6
  • 1
    The indentation is not correct. Please fix to make this code at least valid. – trincot Jul 25 '22 at 11:55
  • `chart` will be a single character string. For such strings `''.join(x) == x`. – chepner Jul 25 '22 at 11:58
  • There's a hint of confusion between `return` and `print` here. The strings written to standard output would *look* like `document` minus the yowls, but you immediately returning the *first* non-vowel character, which ends the loop (and the function) prematurely. You want to *accumulate* the non-vowel characters in a list, then use `join` on that list *after* the loop. – chepner Jul 25 '22 at 12:00
  • Since you aren't modifying the argument in-place, you need to save the return value as well: `vowelless = remove_vowels("document")`. – chepner Jul 25 '22 at 12:00

2 Answers2

2

Try correcting your indentation:

def remove_vowels(text: str) -> str:
    vowels = set("aeioyu")
    text_without_vowels = []
    for chart in text:
        if chart.lower() not in vowels:
            text_without_vowels.append(chart)
    return ''.join(text_without_vowels)

print(remove_vowels("document"))

You could also consider utilizing a comprehension:

def remove_vowels(text: str) -> str:
    vowels = set("aeioyu")
    return ''.join(chart for chart in text if chart.lower() not in vowels)

print(remove_vowels("document"))

Output:

dcmnt
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

if first 'document' charecter is not vowels, your code make it return and exit function.

def remove_vowels(document: str) -> str:    
    vowels = "aeiou"  
    document = document.lower()
    tmpStr = ''
    for chart in document:
        if  chart not in vowels:
            tmpStr = tmpStr + chart
    print(tmpStr)
    return (tmpStr)     

remove_vowels("document")

ksc
  • 11
  • 1
  • 1
    Using `+` for string concatenation in Python creates a copy each time. Using `join` like the OP is trying to do is better inside a loop. – Sash Sinha Jul 25 '22 at 12:09
  • @SashSinha -- with CPython there's an optimization that causes the copying of characters to be done far less often in a loop. See [CPython: Why does += for strings change the id of string variable](https://stackoverflow.com/questions/54006987/cpython-why-does-for-strings-change-the-id-of-string-variable) – DarrylG Jul 25 '22 at 12:46