[英]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).基本上我想返回一个
without a vowel
的字符串(我猜这是一个常见的挑战)。 This is similar to other challenges on CodeWars I have done, still uncompleted due to this.这与我在 CodeWars 上完成的其他挑战类似,因此仍未完成。 I have a for loop within a function.
我在 function 中有一个 for 循环。 I call the function to return value.
我调用 function 来返回值。
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).这是针对 Codewar 挑战的,所以我需要返回值而不是打印、记录(我知道)。 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!"
我期待
"Ths wbst s fr lsrs LL!"
by returning but I get None
.通过返回但我得到
None
。
https://www.codewars.com/kata/52fba66badcd10859f00097e/train/python Source ^ https://www.codewars.com/kata/52fba66badcd10859f00097e/train/python来源^
To remove vowels from strings, the quickest way would be to use str.replace
.要从字符串中删除元音,最快的方法是使用
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!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.