2017-10-21 169 views
0

我试图通过ascii索引来搜索caesar cipher程序,该范围> = 32和< = 126。当我到达最后一个打印输出时,我得到一些字符不在这个范围内。我已经尝试了循环和while循环,但不断收到错误。使用索引范围搜索ascii

我很抱歉,如果我没有发布这个正确。这是我的第一篇文章。

感谢您的任何帮助。

def cipher(phrase,shift): 

     x = list(str(phrase)) 
     xx = ''.join(list(str(phrase))) 

     yy = [] 
     print(x) 
     for c in xx: 
      yy.append(chr(ord(c)+shift)) 

     return ''.join(yy) 

    print(cipher('ABCDE', 97 - 65)) 
    print(cipher('abcde', 65 - 97)) 
    print(cipher(' !\"#$', 95))  

和我的输出是:

['A', 'B', 'C', 'D', 'E'] 
abcde 
['a', 'b', 'c', 'd', 'e'] 
ABCDE 
[' ', '!', '"', '#', '$'] 
+0

什么是你指定'x'和'xx'行的目的是什么?我不认为你需要这些。你可以直接在'phrase'上迭代。 – 2017-10-21 22:01:17

+0

为什么最后一次打印的转换是95? – utengr

+1

当你运行'print(cipher('!\“#$',95))'你会把所有的字符移到126以上。那么你想要达到什么效果? – gommb

回答

0

这应该工作(注意,我清理你的代码了一下):

def cipher(phrase, shift): 

    x = list(str(phrase)) 
    yy = '' 
    print(x) 
    for c in phrase: 
     dec = ord(c) + shift 
     while dec < 32: 
      dec = 127 - (32 - dec) 
     while dec > 126: 
      dec = 31 + (dec - 126) 
     yy += (chr(dec)) 

    return yy 

print(cipher('ABCDE', 97 - 65)) 
print(cipher('abcde', 65 - 97)) 
print(cipher(' !\"#$', 95)) 

输出是:

['A', 'B', 'C', 'D', 'E'] 
abcde 
['a', 'b', 'c', 'd', 'e'] 
ABCDE 
[' ', '!', '"', '#', '$'] 
!"#$ 
+0

感谢您的帮助,我真的很感激它,代码编辑起作用 – Jasper

+0

这是不是就像在原代码中执行'cipher('!“#$',0)'一样? – 2017-10-21 22:27:38

+1

@Wyatt是的,但我认为这只是一个测试,以确保它正确包装。 – gommb

0

我很好奇寻找使用mo的解决方案dulo与不从0开始的范围,所以这里是这样的:

def cipher(phrase, shift): 
    """Shift phrase; return original and shifted versions.""" 
    collector = [] 
    for c in phrase: 
     i = ord(c) 
     if i < 32 or i > 126: 
      raise ValueError('Char not in range [32, 126]: %s' % c) 
     # Shift into range [0, 95) 
     i -= 32 
     # Apply cipher shift 
     i += shift 
     # Push the shifted value back into [0, 95) if necessary 
     i %= 95 
     # Shift back into range [32, 126] 
     i += 32 
     # Convert to char 
     d = chr(i) 
     collector.append(d) 
    return phrase, ''.join(collector) 

print(cipher('ABCDE', 97 - 65)) 
# -> ('ABCDE', 'abcde') 
print(cipher('abcde', 65 - 97)) 
# -> ('abcde', 'ABCDE') 
print(cipher(' !"#$', 95)) 
# -> (' !"#$', ' !"#$')