[英]How to get consonant repeated, but not vowel in Python
我有兩個功能,第一個與第二個相關,它編碼字母是元音(True)還是輔音(False)。
def vowel(c):
"""(str) -> bool
Return whether the string c is a vowel.
>>> vowel('e')
True
>>> vowel('t')
False
"""
for char in c:
if char.lower() in 'aeiou':
return True
else:
return False
def repeated(s, k):
"""(str) -> str
Return a string where consonants in the string s is repeated k times.
>>> repeated('', 24)
''
>>> repeated('eoa', 2)
'eoa'
>>> repeated('m', 5)
'mmmmm'
>>> repeated('choice', 4)
'cccchhhhoicccce'
"""
result = ''
for c in s:
if c is not vowel(c):
result = result + (c * k)
return result
這就是我要使用的功能,但是示例失敗並且不會跳過元音。
repeat('eoa', 2)
Expected:
'eoa'
Got:
'eeooaa'
提前致謝!
兩件事情。 在vowel
功能中,不需要循環。 您要發送一個字符,因此只需要檢查一下即可:
def vowel(c):
if c.lower() in 'aeiou':
return True
else:
return False
要么:
def vowel(c):
return True if c.lower() in 'aeiou' else False
然后, repeated
使用,不要使用c is not vowel(c)
。 可以比較字符c
的標識是否等於True/False
。 只需直接使用從vowel
返回的值,並有條件地添加到result
:
def repeated(s, k):
result = ''
for c in s:
if not vowel(c):
result += (c * k)
else:
result += c
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.