Python 单字符输出未返回任何内容
这应该是一个函数的一部分,该函数将辅音替换为Python 单字符输出未返回任何内容,python,Python,这应该是一个函数的一部分,该函数将辅音替换为“$”,直到到达“ch”字符,然后停止 示例: 元音\u或\u非('abcdeAghi','A')应返回'A$$$$e' 元音\u或\u非('aaaaA','A')应返回'aaaa' 我的问题是,如果输入字符串只有一个字符长,它什么也做不了元音字母u或非(a,X)应返回a,元音字母u或非(X,a)应返回$。其他一切都很好。我试图修复它,但我仍然没有看到任何错误的代码,但再次我是一个初学者!任何帮助都将不胜感激 def vowels_or_not (st
“$”
,直到到达“ch”
字符,然后停止
示例:
元音\u或\u非('abcdeAghi','A')
应返回'A$$$$e'
元音\u或\u非('aaaaA','A')
应返回'aaaa'
我的问题是,如果输入字符串只有一个字符长,它什么也做不了元音字母u或非(a,X)
应返回a
,元音字母u或非(X,a)
应返回$
。其他一切都很好。我试图修复它,但我仍然没有看到任何错误的代码,但再次我是一个初学者!任何帮助都将不胜感激
def vowels_or_not (st, ch)
vowels = ('a','e','i','o','u','A','E','I','O','U')
flag = True
a = 0
aux = ''
while flag is True:
for i in range(len(st)):
if (st[i] == ch):
flag = False
break
else:
if (st[i] in vowels):
aux = aux + st[i]
a = a + 1
if (st[i] not in vowels):
aux = aux + '$'
a = a + 1
return aux
您的代码在这些情况下不起作用,因为您的
while
循环永远不会结束。一旦for
循环退出,while
循环就会一直持续下去
要修复代码,只需在循环结束后设置flag=False
:
def vowels_or_not (st, ch):
vowels = ('a','e','i','o','u','A','E','I','O','U')
flag = True
a = 0
aux = ''
while flag is True:
for i in range(len(st)):
if (st[i] == ch):
flag = False
break
else:
if (st[i] in vowels):
aux = aux + st[i]
a = a + 1
if (st[i] not in vowels):
aux = aux + '$'
a = a + 1
flag = False # <-- Right here
return aux
为了使代码更好一点,不要使用索引。Python允许您直观地迭代字符串:
def vowels_or_not(word, character):
vowels = 'aeiou'
output = ''
before, middle, after = word.partition(character)
for letter in before:
if letter.lower() in vowels:
output += letter
else:
output += '$'
return output + middle + after
问题是,如果
st
中的最后一个字符与ch
中的最后一个字符不同,则while循环永远不会结束
但您并不真正需要while循环,因为它是冗余的,您只需要for循环:
def vowels_or_not(st, ch):
vowels = ('a','e','i','o','u','A','E','I','O','U')
a = 0
aux = ''
for i in range(len(st)):
if (st[i] == ch):
break
else:
if (st[i] in vowels):
aux = aux + st[i]
a = a + 1
if (st[i] not in vowels):
aux = aux + '$'
a = a + 1
return aux
或更长版本
vowels = 'aeiouAEIOU'
def vowels_or_not_longer_version (st, ch):
ret=''
for i in st.partition(ch)[0]:
ret+= i in vowels and i or '$'
return ret
这不是您正在运行的实际代码;函数定义后缺少
:
,因此无法运行。还有什么不同吗?哈,我想是的!我们最近刚刚了解了while循环,我从未使用过它们,所以我想我会在这里使用。谢谢谢谢你的提示,以后我会记住的!我还没有了解到这一点,所以我不想让人觉得我是在作弊什么的。
>>> vowels_or_not('a', 'X')
'a'
>>> vowels_or_not('aaaAX', 'X')
'aaaA'
>>> vowels_or_not('aaabX', 'X')
'aaa$'
import functools # for python3 reduce (working under python2 too)
vowels = 'aeiouAEIOU'
def vowels_or_not (st, ch):
return functools.reduce(lambda a,b:a+(b in vowels and b or '$'), st.partition(ch)[0],'')
vowels = 'aeiouAEIOU'
def vowels_or_not_longer_version (st, ch):
ret=''
for i in st.partition(ch)[0]:
ret+= i in vowels and i or '$'
return ret