在python中,a变成z,b变成y,abcd变成zyxw…等等

2024-06-26 15:02:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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


Tags: orandin算法forinputstringif
2条回答

既然你没说你想处理大写字母,这里有一个简单的答案:

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

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

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

^{pr2}$

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

>>> 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!'

您可以使用以下方法。
创建一个字典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方法实现:

^{pr2}$


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

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

相关问题 更多 >