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

Time:07-25

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

CodePudding user response:

Try correcting your indentation:

def remove_vowels(text: str) -> str:
    vowels = set("aeioyu")
    text_without_vowels = []
    for chart in text.lower():
        if chart 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.lower() if chart not in vowels)

print(remove_vowels("document"))

Output:

dcmnt

CodePudding user response:

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

  • Related