首页 > 解决方案 > 将字符串的所有字母移动某个步骤

问题描述

import ast  
in_string = input()  
lis = ast.literal_eval(in_string)  
st = lis[0]  
step = lis[1]  
alphabets = 'abcdefghijklmnopqrstuvwxyz'  
password = ''  
for letter in st:  
    if letter in alphabets:  
        index_val = alphabets.index(letter) - (step)  
        password += alphabets[index_val]  

print(password)

我得到的输出是'utgtgt'。我想要'utGtGt'。对此的帮助将不胜感激。

标签: pythonpython-3.xstringloopsindexing

解决方案


string 模块具有创建转换字典的方法和一个translate 方法来完全按照您的意愿进行操作:

st = "baNaNa"
step = 7
alphabets = 'abcdefghijklmnopqrstuvwxyz'
alph2 = alphabets.upper() 

# lower case translation table
t = str.maketrans(alphabets, alphabets[-step:]+alphabets[:-step])

# upper case translation table
t2 = str.maketrans(alph2, alph2[-step:]+alph2[:-step])

# merge both translation tables
t.update(t2)

print(st.translate(t)) 

输出:

utGtGt

你给它原始字符串和一个相等的长字符串来映射字母并使用str.translate(dictionary).

切片字符串等同于:

print(alphabets)
print(alphabets[-step:]+alphabets[:-step])

abcdefghijklmnopqrstuvwxyz
tuvwxyzabcdefghijklmnopqrs

这就是你的step目的。


如果您从未见过使用字符串切片,请参阅了解切片表示法。


推荐阅读