繁体   English   中英

使用 ascii_letters 用下一个替换字母时出错

[英]Error in replacing alphabets with the next one using ascii_letters

问题是一个已知的问题:给定一个句子,返回所有字母在字母表中被 1 转置的句子,但前提是字母是 ay。

我知道类似的问题已经在这里问过很多次了,但是我在我的案例中应用的解决方案实际上来自这些 stackoverflow 答案之一,并且 function 仍然保持领先 2-3 个字母:

from string import ascii_letters

def inverter(sentence):
    for x in sentence:
        if x in ascii_letters and x!= 'z' and x != ' ':
            sentence = sentence.replace(x,ascii_letters[ascii_letters.index(x)+1])
        else:
            sentence = sentence
    return sentence

sent3 = 'a quick brown fox jumps over the lazy dog'

inverter(sent3)

Output:

'c uwkem cuqzq hqz kwnqu qwfu uif mczz eqh'

突变循环中可能出了什么问题?

使用ord将每个特定字符转换为其数字形式,添加1 ,然后使用chr将 integer 转换回字符:

from string import ascii_letters

def inverter(sentence):
    a_to_y = ascii_letters[:25]
    s = ''
    for i in sentence:
        if i in a_to_y:
            i = chr(ord(i) + 1)
        s += i
    return s

sent3 = 'a quick brown fox jumps over the lazy dog'

print(inverter(sent3))

Output:

b rvjdl cspxo gpy kvnqt pwfs uif mbzz eph

这是一个单行:

def inverter(sentence):
    return ''.join([chr(ord(i) + 1) if i in 'abcdefghijklmnopqrstuvwxy' else i for i in sentence])

sent3 = 'a quick brown fox jumps over the lazy dog'

print(inverter(sent3))

这就是您的for循环不起作用的原因:

str.replace方法用另一个指定的字符串替换所有出现的指定字符串,而不仅仅是一个。

假设您的句子是"apple anna"

for x in sentence: ,第一个字母将是"a"

由于"a"满足条件if x in ascii_letters and x:= 'z' and x != ' ': ,因此"a"将被替换为"b" 但不仅仅是"a" ,所有其他该字符串中的"a"

当迭代到达下一个"a"时, "a"已经是"b"了,所以之前的"a"将被替换为"c" ,然后下一个之前的"c""d"

这同样适用于您的字符串,其中包含大部分字母。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM