如何使用Python根据ascii顺序移动字符

如何使用Python根据ascii顺序移动字符,python,arrays,string,character,ascii,Python,Arrays,String,Character,Ascii,例如,hello,world应转换为ifmmo,xpsme。(a->b,b->c,…,z->a) 在C语言中,只需编写print ch+1执行换档操作。但是,在尝试使用Python时,我得到: >>> [i+1 for i in "hello, world"] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concate

例如,
hello,world
应转换为
ifmmo,xpsme
。(
a
->
b
b
->
c
,…,
z
->
a

在C语言中,只需编写
print ch+1执行换档操作。但是,在尝试使用Python时,我得到:

>>> [i+1 for i in "hello, world"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>[i+1代表“你好,世界”]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法连接'str'和'int'对象
看看这个

a = [chr(ord(i)+1) for i in "hello, world"]
print ''.join(map(str,a))


下面是在字符串中移动字符的函数。我还更改了这两个函数中的逻辑,以提高清晰度

  • 使用列表理解:

  • 使用自定义函数(具有普通逻辑):

样本运行:

# with shift 1
>>> shift_string(my_string, 1)
'ifmmp, xpsme'

# with shift 2
>>> shift_string(my_string, 2)
'jgnnq, yqtnf'

这个问题的答案对你的问题有效。@Maurice确实如此。我现在该怎么办?删除这篇文章,投一票(我已经投了),或者写下答案?
import string
alph_string = string.ascii_letters # string of both uppercase/lowercase letters

def shift_string(my_string, shift):
     return ''.join([chr(ord(c)+shift) if c in alph_string else c for c in my_string])
import string
my_alphas = string.ascii_lowercase  # string of lowercase alphabates 

def shift_string(my_string, shift):
    new_string = ''
    for i in my_string:
        if i in my_alphas:
            pos = my_alphas.index(i) + shift
            if pos >  len(my_alphas):
                pos -= len(my_alphas)
            new_string += my_alphas[pos]
        else:
            new_string += i
    return new_string
# with shift 1
>>> shift_string(my_string, 1)
'ifmmp, xpsme'

# with shift 2
>>> shift_string(my_string, 2)
'jgnnq, yqtnf'