Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python更改字母_Python - Fatal编程技术网

使用Python更改字母

使用Python更改字母,python,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:

问题陈述:

让函数
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())
def字体更改(str):
对于范围(0,len(str))中的i:
a=ord(str[i])
如果a==122:
str=str.replace(str[i],'a',1)
elif a==90:
str=str.replace(str[i],'a',1)

elif(a>=65、a=97和a您正在处理字符串中的“t”两次,首先将s替换为“t”,然后将“t”再次替换为“u”,这也是字符串中的第一次替换

def LetterChanges(line): 
    result = ""
    for i in line:
        a=ord(i)
        if a == 122 or a == 90:
            result += 'A'
        elif (a >= 65 and a <= 90) or (a >= 97 and a <= 122):
            a = a + 1
            char = chr(a)
            if char in ('e', 'i', 'o', 'u'):
                char = char.upper()
            result += char
        else:
            result += i
    return(result)
def字体更改(行):
result=“”
就我而言:
a=ord(i)
如果a==122或a==90:
结果+=“A”

elif(a>=65、a=97和a您正在处理字符串中的“t”两次,首先将s替换为“t”,然后将“t”再次替换为“u”,这也是字符串中的第一次替换

def LetterChanges(line): 
    result = ""
    for i in line:
        a=ord(i)
        if a == 122 or a == 90:
            result += 'A'
        elif (a >= 65 and a <= 90) or (a >= 97 and a <= 122):
            a = a + 1
            char = chr(a)
            if char in ('e', 'i', 'o', 'u'):
                char = char.upper()
            result += char
        else:
            result += i
    return(result)
def字体更改(行):
result=“”
就我而言:
a=ord(i)
如果a==122或a==90:
结果+=“A”
elif(a>=65和a=97和a这里是另一个尝试:

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')
这里是另一个尝试:

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')
你的错误在这里: 当您正在替换时,您并不关心字符在何处被替换,所以当您提供
sent
输入时,它是如何进行的 在替换n之后,我们得到了类似
tfot
的字符串,现在在下一次迭代中,您在原始字符串中遇到的下一个字母是
t
,因此它将替换被替换字符串中的第一个字母
t
,因此,“tfot”变为“ufot”,而最后一个t没有被替换

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

函数式编程,不使用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

不使用ord()或循环的函数式编程take将与其他非字母字符一起使用,我认为:

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

下面是使用
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

下面是使用
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
更换这条线
str=str.replace(str[i],char,1)
str=str[:i]+char+str[i+1:][/code>
@Pankaj78691回答此问题的原因是正确的!!

更换此行
str=str.replace(str[i],char,1)
str=str[:i]+char+str[i+1:][/code>

@Pankaj78691回答此问题的原因是正确的!!

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

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)

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

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)

这是我的算法版本

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

这是我的算法版本

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

所以输入cz应该变成dA,对吗?如果输入是'sen',你告诉o/p将是'tfo',那么大写呢?我建议你构建一个全新的字符串,而不是修改现有的字符串(尽管有问题陈述,但这几乎是你正在做的,因为字符串是不可变的)不要对方法名使用“CamelCase”,只对“Classes”使用。函数名应该是小写的,并根据需要用下划线分隔单词,以提高可读性。看到了吗,输入cz应该变成dA,对吗?如果输入是“sen”,你告诉o/p将是“tfo”,那么大写呢?我建议你构建一个全新的字符串,而不是修改现有的一个函数(尽管有问题,但这几乎是您正在做的,因为字符串是不可变的)不使用“CamelCase”作为方法名,只用于“类”。函数名应该是小写的,必要时用下划线分隔单词以提高可读性。请参阅