2020-04
15

字符偏移加密

By xrspook @ 13:28:09 归类于: 扮IT

本来我根本没考虑字母以外的那些怎么办,测试过参考答案以后,发现原来字母以外的东西原始输出,于是我也这般弄了,等于再加一个是否字母的判断,折腾。不告诉人家怎么把字符合并成字符串,我就只好准备两个对象二人转连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def rotate_word(something, n): # a-z: 97-122, A-Z: 65-90
    newletter1 = ''
    for letter in something:
        if ord(letter) < ord('A') or ord('Z') < ord(letter) < ord('a') or ord('z') < ord(letter):
            newletter2 = newletter1 + letter
        else:
            if ord(letter) + n > ord('z'):
                newletter2 = newletter1 + chr(ord(letter) + n - 26)
            elif ord('a') > ord(letter) + n > ord('Z'):
                newletter2 = newletter1 + chr(ord(letter) + n - 26)
            else:
                newletter2 = newletter1 + chr(ord(letter) + n)
        newletter1 = newletter2
    return newletter2
something = input('please write something: ')
n = int(input('how many shifts do you want: '))
print('before:', something)
print('after :', rotate_word(something, n))
# please write something: IBM
# how many shifts do you want: -1
# before: IBM
# after : HAL
# please write something: g858^h{O
# how many shifts do you want: 6
# before: g858^h{O
# after : m858^n{U
© 2004 - 2024 我的天 | Theme by xrspook | Power by WordPress