简体   繁体   中英

How do I return a value within a loop within a function?

I have this almost figured it out but there is one thing. Basically I want to return a string without a vowel (a common challenge I guess). This is similar to other challenges on CodeWars I have done, still uncompleted due to this. I have a for loop within a function. I call the function to return value.

For some reason, I'm returning empty or rather "None", yet I get the result I wanted by printing. On the same line and indenting.

This is for a Codewar challenge, so I need to return values instead of, printing, logging (I know). I asked for a friend, hours of researching but nothing could help me.

def disemvowel(string):
    #aeiou
    vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    aList = list(string) #'' to [...]

    for x in aList:
      for y in vowel:
        if x == y: 
          #print(x)
          aList.remove(x)
    print(''.join(aList)) # "Ths wbst s fr lsrs LL!"
    return(''.join(aList)) # Nothing shows up here...


I expect the output of "Ths wbst s fr lsrs LL!" by returning but I get None .

https://www.codewars.com/kata/52fba66badcd10859f00097e/train/python Source ^

To remove vowels from strings, the quickest way would be to use str.replace .

def remove_vowels(msg):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    for vowel in vowels:
        msg = msg.replace(vowel, '')
    return msg

Use a list comprehension:

def remove_vowels(msg):
    return ''.join(c for c in msg if c.lower() not in {'a', 'e', 'i', 'o', 'u'})

Examples:

>>> remove_vowels("Lorem ipsum dolor sit amet.")
'Lrm psm dlr st mt.'
>> remove_vowels("This is it")
'Ths s t'
>>> remove_vowels("This website is for losers LOL!")
'Ths wbst s fr lsrs LL!'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM