a变为z,b变为y。 abcd在python

时间:2017-10-21 20:40:15

标签: python string

def string_transf():
    input('Enter a word or string')
    #letters = 'abcdefghijklmnopqrstvwxyz'
    #for i in letters:
            #i+=

    if c >= 'a' and c <='z':
        i = 'z' - c + 'a'
        print(i)

我试图想出一个算法,但我迷路了。

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法。
创建一个字典my_map,其中描述了字符的翻译:

import string
ascii_alph = string.ascii_lowercase

my_map = dict(zip(ascii_alph, ascii_alph[::-1]))

str_input = 'abcd'
str_output = ''.join(my_map[c] for c in str_input) # assume every c in my_map

print(str_output) # zyxw


您也可以使用translate方法实现它:

# my_map = string.maketrans(ascii_alph, ascii_alph[::-1]) # Python 2
my_map = str.maketrans(ascii_alph, ascii_alph[::-1]) # Python 3

str_input = 'abcd'
str_output = str_input.translate(my_map)

print(str_output) # zyxw


对于一般情况(ASCII大写和其他字符),您始终可以展开'my_map'字典。

请注意,所描述的方法非常灵活,因为它允许您不仅针对字母表的反转进行翻译。

答案 1 :(得分:0)

由于你没有说你想要处理大写字母,这里有一行答案:

>>> ''.join(chr(122 - ord(c) + 97) for c in 'abcd')
'zyxw'

其中122为ord('z'),97为ord('a')ord函数将字符转换为Unicode代码点,而chr函数则相反。

如果您愿意,可以跳过非小写字符:

>>> ''.join(chr(122 - ord(c) + 97) for c in 'abcdEFG' if 'a' <= c <= 'z')
'zyxw'

如果要按照相同的模型处理大写:

>>> def inv(c):
...  if 'a' <= c <= 'z':
...   return chr(122 - ord(c) + 97)
...  if 'A' <= c <= 'Z':
...   return chr(90 - ord(c) + 65)
...  return c
... 
>>> ''.join(inv(c) for c in 'Hello world!')
'Svool dliow!'