python - Python 中的文本移位函数

标签 python python-2.7

我正在编写代码,以便您可以将文本沿字母表移动两个位置:'ab cd' 应该变为 'cd ef'。我正在使用 Python 2,这是我目前得到的结果:

def shifttext(shift):
    input=raw_input('Input text here: ')
    data = list(input)
    for i in data:
        data[i] = chr((ord(i) + shift) % 26)
        output = ''.join(data)
    return output
shifttext(3)

我收到以下错误:

File "level1.py", line 9, in <module>
    shifttext(3)
File "level1.py", line 5, in shifttext
    data[i] = chr((ord(i) + shift) % 26)
TypError: list indices must be integers, not str

所以我必须以某种方式将字母更改为数字?但我想我已经做到了?

最佳答案

您正在遍历字符列表,因此 i 是一个字符。然后,您尝试使用 i 字符作为索引将其存储回 data。那是行不通的。

使用 enumerate() 获取索引值:

def shifttext(shift):
    input=raw_input('Input text here: ')
    data = list(input)
    for i, char in enumerate(data):
        data[i] = chr((ord(char) + shift) % 26)
    output = ''.join(data)
    return output

您可以使用生成器表达式简化它:

def shifttext(shift):
    input=raw_input('Input text here: ')
    return ''.join(chr((ord(char) + shift) % 26) for char in input)

但是现在您会注意到您的 % 26 不起作用; ASCII 代码点在 26 之后开始:

>>> ord('a')
97

您需要使用 ord('a') 值才能使用模数;减法将您的值置于 0-25 范围内,然后您再次添加它:

    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26) + a) for char in input)

但这只适用于小写字母;这可能没问题,但您可以通过小写输入来强制执行此操作:

    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in input.lower())

如果我们然后从函数中请求输入以专注于做好一项工作,这将变为:

def shifttext(text, shift):
    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in text.lower())

print shifttext(raw_input('Input text here: '), 3)

并在我看到的交互式提示中使用它:

>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Cesarsalad!
fhvduvdodgr

当然,现在标点符号被带走了。上次修订,现在仅移动字母:

def shifttext(text, shift):
    a = ord('a')
    return ''.join(
        chr((ord(char) - a + shift) % 26 + a) if 'a' <= char <= 'z' else char
        for char in text.lower())

我们得到:

>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Ceasarsalad!
fhdvduvdodg!

关于python - Python 中的文本移位函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424500/

相关文章:

python - background_task.py 不显示消息 - Python

python - 将整个Python标准库编译为字节码是否可能且可行?

python - 迭代器作为 bool 语句?

python - Boto connect_xxx 方法和连接池

Udemy 类(class)的 Python 里程碑项目

python - 找到用于最小化函数的输入向量

Python 扩展 : symbol(s) not found for architecture x86_64 error

python - 为什么我的堆排序不起作用?

linux - 在 Amazon Linux 虚拟服务器上的 Python 2.7 上安装 GDAL

python - 我无法打开manage.py