一个函数,返回一系列字母,顺序相同,但任何元音显示为*而任何字母显示为%

2024-10-01 09:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个以字母列表为参数的函数。函数应该以相同的顺序返回字母列表,除了元音字母显示为*和任何字母字母显示为%。这是我的解决方案,请告诉我为什么不起作用:

lst [‘s’, ‘a’, ‘l’, ‘l’, ‘y’]

def letter_list(word):
newLetters = []
    for char in range(0, len(word) -1):
    if char in ‘aeiou’: 
        char = “ * “  
        if char.lower() == ‘l’  char = ‘%’ : 
          newLetters = newLetters + char
return newLetters

print letter_list(“Sally”)

Tags: 函数in列表参数if顺序字母解决方案
3条回答
def letter_list(word):
    newLetters = word.lower()
    newLetters = newLetters.replace("a", "*").replace("e", "*").replace("i", "*").replace("o", "*").replace("u", "*").replace("l", "%")
    return newLetters

print(letter_list("Sally"))

你的问题和解决办法有些模棱两可。你的意思是函数将获取字母/字符列表,但你发送的是整个单词

以下是解决方案:

def letter_list(word):
    newLetters = []
    for char in word:
        if char in "aeiou":
            char = "*"
        if char.lower() == 'l':
            char = '%'
        newLetters.append(char)
    return newLetters

# sending word as list of chars
print(letter_list(list("Sally")))

您的代码不起作用,因为您对字符串和字符使用了所有错误的标记。除此之外,你 地址:

  • lst与其元音之间缺少=
  • 代替"
  • 代替'

你的缩进是错误的-你必须缩进所有属于你的函数的东西(你应该一致的缩进,而不是4个字符,然后制表符,然后2个字符等等)

您还可以使用理解:

def letter_list(word):
    return ''.join( c if c not in 'aeiou' else '*' for c in word).replace('l','%')
                    # use the character if not in aeiou else *  
                    # replace l after the fact                     

print(letter_list("Sally"))

输出:

S*%%y

相关问题 更多 >