def long_string(str):
vow_list = ["a","e","i","o","u"]
for v in vow_list:
new_str = str.replace(v,"*")
return(new_str)
long_string("Why is this code not working?")
这里有两个问题:
- 您使用名称
str
作为参数,这与Python中字符串类型的名称冲突 - 您将在替换列表中的第一个元音后立即返回字符串,而不是保存字符串以供进一步替换
以下代码适用于我:
def long_string(string):
vow_list = ["a","e","i","o","u"]
for v in vow_list:
string = string.replace(v,"*")
return string
print(long_string("Test string"))
另一个注意事项:这个代码只处理小写元音。如果您也想处理大写字母,请将"A"
、"E"
、"I"
、"O"
和"U"
添加到vow_list
中。
根据注释说明回答:选择一个随机元音,替换该元音的所有出现。
import random
text = "Why is this code not working?"
vowels = "aeiouAEIOU"
vowel = random.choice(vowels)
text.replace(vowel, "*")
CCD_ 8从序列中挑选一个随机元素。字符串也是序列,"aeiou"
看起来比["a","e","i","o","u"]
更漂亮(而且内存效率略高,尽管这不是问题(。