我如何使代码只移动字母而不移动空格?

2024-07-05 09:23:01 发布

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

#get string and shift from user

string = input('Please enter a string to be ciphered: ')
shift = input('Please enter a shift amount between 0 and 25: ')

#strings are immutable so it must be converted to a list
s=list(string)

#now this will convert each character based on the shift

for i in range(0,len(s)):
    s[i]=chr(ord(s[i]) + int(shift))


print ("".join(s))

Tags: andtofrominputgetstringshiftbe
2条回答

您所要做的就是检查当前字符是否不是要跳过的字符

for i in range(0,len(s)):
    #If not a space, cipher this character.
    if s[i] != ' ':
        s[i]=chr(ord(s[i]) + int(shift))

但是,您的一个字符有可能被加密到一个空格中,在这种情况下,当反转密码时,该字符将被跳过

同样,像这样的简单密码至少不应该被认为是安全的

在移位之前,应该调用方法str.alpha,以确保所选元素是字母表

for i in range(0,len(s)):
    if elem.isaplha():
        s[i]=chr(ord(s[i]) + int(shift))

不过,你在这里做了很多工作。为什么不使用理解表达

s = ''.join(chr(ord(elem) + shift) if elem.isalpha() else elem for elem in s)

或者如果你够冒险的话

s = ''.join([elem, chr(ord(elem) + shift)][elem.isalpha()] for elem in s)

最后你检查了string.makestransstr.translate来进行转换吗

from string import maketrans, ascii_alpha
s = s.translate(maketrans(ascii_alpha[shift:] + string.ascii_alpha[:shift])

相关问题 更多 >