Skip to content
Advertisement

Why .join() didn’t work properly? (Python)

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")   

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement