Python中的文本移位功能 [英] Text Shift function in Python

查看:93
本文介绍了Python中的文本移位功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing code so you can shift text two places along the alphabet: 'ab cd' should become 'cd ef'. I'm using Python 2 and this is what I got so far:

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

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

So I have to change the letter to numbers somehow? But I thought I already did that?

推荐答案

看起来你正在做 cesar-cipher 加密,所以你可以尝试这样的事情:

Looks you're doing cesar-cipher encryption, so you can try something like this:

strs = 'abcdefghijklmnopqrstuvwxyz'      #use a string like this, instead of ord() 
def shifttext(shift):
    inp = raw_input('Input text here: ')
    data = []
    for i in inp:                     #iterate over the text not some list
        if i.strip() and i in strs:                 # if the char is not a space ""  
            data.append(strs[(strs.index(i) + shift) % 26])    
        else:
            data.append(i)           #if space the simply append it to data
    output = ''.join(data)
    return output

输出:

In [2]: shifttext(3)
Input text here: how are you?
Out[2]: 'krz duh brx?'

In [3]: shifttext(3)
Input text here: Fine.
Out[3]: 'Flqh.'

strs[(strs.index(i) + shift) % 26]: 上面一行表示在strsi的索引代码>,然后将移位值添加到它.现在,在最终值(索引+移位)上应用 %26 以获得移位的索引.当传递给 strs[new_index] 时,这个移位的索引会产生所需的移位字符.

strs[(strs.index(i) + shift) % 26]: line above means find the index of the character i in strs and then add the shift value to it.Now, on the final value(index+shift) apply %26 to the get the shifted index. This shifted index when passed to strs[new_index] yields the desired shifted character.

这篇关于Python中的文本移位功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆