python - 将字符串的所有字母移动某个步骤
问题描述
- 输入:
['baNaNa', 7]
#字符串和步长 - required output :
'utGtGt'
# 字符串的每个字符向后移动步长
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'。对此的帮助将不胜感激。
解决方案
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
目的。
如果您从未见过使用字符串切片,请参阅了解切片表示法。
推荐阅读
- parallel-processing - Cython:“with nogil, parallel()”中的两个 prange 可能吗?
- winapi - CreateFile winapi 在卷 C 上失败
- reactjs - ReactJS UseEffect 方法中的渲染循环问题
- android - react-native-community / react-native-netinfo 监听器不在android上工作
- python - 使用python脚本使用coverage.py对文件进行代码覆盖
- cassandra - Dse opscenter 未启动
- python - 如何上传 jpg 文件并将其保存在 restplas flask api 中?
- android - messing().onNotificationOpenedApp 永远不会触发,messaging().getInitialNotification() 会被触发,但 remoteMessage 始终为空
- c - C语言中的%f和%F有什么区别?
- r - R中的Vlookup / Match函数用于R中的连续列