Warm tip: This article is reproduced from serverfault.com, please click

python-使用ascii_letters将字母替换为下一个字母时出错

(python - Error in replacing alphabets with the next one using ascii_letters)

发布于 2020-11-28 22:29:17

问题是一个已知的问题:给定一个句子,请返回该句子,其所有字母在字母表中均由1换位,但前提是该字母为ay。

我知道这里曾多次问过类似的问题,但是我在我的案例中应用的解决方案实际上来自这些stackoverflow答案之一,并且该功能仍然不断向前跳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)

输出:

'c uwkem cuqzq hqz kwnqu qwfu uif mczz eqh'

突变循环中可能出什么毛病?

Questioner
Anish
Viewed
11
Ann Zen 2020-11-29 11:58:00

使用ord到每个特定字符的转换成其编号的形式,添加1和使用chr转换的整数回一个字符:

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

输出:

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"在字符串s

通过迭代到达下一个时间"a"时,"a"就已经是一个"b",那么前者"a"将与被替换"c",然后将成为下一个前"c""d"

同样的情况也适用于你的字符串,其中包含大多数字母。