使用Python更改字母

时间:2018-07-11 06:14:10

标签: python

问题陈述:

  

让函数LetterChanges(str)接受要传递的str参数,并使用以下算法对其进行修改。将字符串中的每个字母替换为字母后面的字母(即c变成d,z变成a)。然后在此新字符串(a,e,i,o,u)中将每个元音大写,最后返回此修改后的字符串。

我的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时,我得到了错误的输出。

8 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

这里是另一个尝试:

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')

答案 2 :(得分:1)

在不使用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

答案 3 :(得分:1)

替换此行 str=str.replace(str[i],char,1)str = str[:i] + char + str[i+1:] @ Pankaj78691回答此问题的原因是正确的!

答案 4 :(得分:0)

您要在字符串中两次处理't',首先将s替换为't',然后再将't'替换为'u'也是字符串中的第一个替换项

if(val < firstHalf[pos])

答案 5 :(得分:0)

这是使用re的另一种方式:

import re

def letter_changes(my_string):
    in_letters = "abcdefghijklmnopqrstuvxyz"
    out_letters = "bcdefghijklmnopqrstuvxyza"

    letter_dict1 = {x:y for x,y in zip(in_letters, out_letters)}
    letter_dict2 = {'a':'A', 'e':'E', 'i':'I', 'o':'O', 'u':'U'}

    for l_dict in [letter_dict1, letter_dict2]:
        pattern = re.compile("|".join(l_dict.keys()))
        my_string = pattern.sub(lambda m: l_dict[re.escape(m.group(0))], my_string)

    return my_string

答案 6 :(得分:0)

这是编写代码的另一种方式:-

def rep_cap(sent):

    sent_rp = ''.join([chr(c) for c in [x+1 for x in [ord(c) for c in sent]]]).replace('{','a') #This thing is done to convert a to b .... z to a 

    final_output = ""

    vowels = ['a','e','i','o','u']
    for i in sent_rp:
        if i in vowels:
            final_output = final_output+i.upper() #convert vowels to upper case
        else :
            final_output = final_output+i

    return final_output   

sent = raw_input("Enter a sentence:")

print rep_cap(sent)

答案 7 :(得分:0)

这是我的算法版本。

def LetterChanges(str):
    result = ''
    vowels = ['a','e','i','o','u']

    for s in str:
        if s.isalpha():
            if ord(s) == 122: #ASCII code of 'z'
                next_letter = chr(97)
            else:
                next_letter = chr(ord(s)+1)

            if next_letter in vowels:
                result += next_letter.upper()
            else:
                result += next_letter

        else:
            result += s

    return result