使用Python更改字母

2024-09-28 21:44:58 发布

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

问题陈述:

Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

我的Python程序是:

def LetterChanges(str):
    for i in range(0,len(str)):
        a=ord(str[i])
        if a==122:
            str=str.replace(str[i],'a',1)
        elif a==90:
            str=str.replace(str[i],'a',1)
        elif (a>=65 and a<=90) or (a>=97 and a<=122):
            a=a+1
            char=chr(a)
            str=str.replace(str[i],char,1)
    for i in range(0,len(str)):
        if str[i]=='a':
            str=str.replace(str[i],'A',1)
        elif str[i]=='e':
            str=str.replace(str[i],'E',1)
        elif str[i]=='i':
            str=str.replace(str[i],'I',1)
        elif str[i]=='o':
            str=str.replace(str[i],'O',1)
        elif str[i]=='u':
            str=str.replace(str[i],'U',1)
    return(str)

print LetterChanges(raw_input())

我的代码的问题是,当我输入sen时,输出是tfo,这是正确的。在

但是当我把sent作为输入时,我得到了错误的输出。在


Tags: andtheinstringreturnitthisreplace
3条回答

再来一次:

def prgrm(n):
    k = ""
    for i in n:
        nxt = chr(97 if i == 'z' else ord(i)+1)
        if nxt in ('a', 'e', 'i', 'o', 'u'):
            nxt = nxt.capitalize()
        k += nxt
    print(k)

prgrm('sen')

函数式编程take,不使用ord()或循环,将在存在其他非字母字符的情况下工作,我认为:

def LetterChanges(str):
    vowels = "aeiou"
    lowers = "abcdefghijklmnopqrstuvwxyza"
    all = lowers.upper() + lowers
    # Map all alphabetical characters
    nxt_str = "".join(map(lambda x: all[all.index(x) + 1] if x in all else x, str))
    # Map the vowels
    return "".join(map(lambda x: x.upper() if x in vowels else x, nxt_str))

print(LetterChanges("sentdZ"))
tfOUEA

你的错误在这里:silpa 当您替换时,您并不关心字符替换的索引,所以当您给出sent输入时,它是如何进行的 替换n之后,我们得到类似tfot的字符串,在下一次迭代中,您在原始字符串中遇到的下一个字母是t,因此它将替换替换字符串中的第一个字母t,因此。”“tfot”变为“ufot”,最后一个t不被替换

相关问题 更多 >