在列表中移动字符

我想用某个指定的位置移动字符 Ex :Input = ['banana', 7]这里 7 是移动位置的步骤。Output = utgtgt. 它应该适用于任何用户输入。用户输入可以是小写和大写。数值是需要移动的位置数


代码:


input_list = ['banana', 7]

message=input_list[0]

n=input_list[1]


list1=[]

for i in message:

    ch = i

    x = chr(ord(ch)-n)

    list1.append(x)

print("".join(list1))


守候你守候我
浏览 131回答 3
3回答

侃侃尔雅

您应该计算给定字符到 的序数的偏移量,将其'a'移动n,得到它的模 26,然后通过添加 back 的序数来获得移动字符的序数'a':改变:x = chr(ord(ch)-n)至:x = chr((ord(ch) - ord('a') - n) % 26 + ord('a'))要同时处理大写字母,您可以先有条件地设置基本字符:base = ord('a' if ch.islower() else 'A') x = chr((ord(ch) - base - n) % 26 + base)演示:https ://repl.it/@blhsing/ClosedElectricEquation

POPMUISE

在@blhsing 答案的基础上,您可以通过列表理解将您的输出放在一行中。"".join([chr((ord(ch) - ord('a') - n) % 26 + ord('a'))for ch in message])>>> 'utgtgt'

倚天杖

小写字母仅占用代码点 97 到 122。如果ord(ch) - n小于 97,则必须环绕。for ch in message:&nbsp; &nbsp; new = ord(ch) - n&nbsp; &nbsp; if new < ord('a'):&nbsp; &nbsp; &nbsp; &nbsp; new += 26&nbsp; &nbsp; list1.append(chr(new))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python