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

Question:

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")   
Asked By: avkpol

||

Answers:

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
Answered By: Sash Sinha

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

Answered By: ksc
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.