【问题标题】:Using an index range to search ascii使用索引范围搜索 ascii
【发布时间】:2017-10-21 21:51:15
【问题描述】:

我正在尝试搜索 ascii 索引以编写一个范围为 >= 32 和

如果我没有正确发布此内容,我深表歉意。这是我的第一篇文章。

感谢您的帮助。

    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
[' ', '!', '"', '#', '$']

【问题讨论】:

  • 分配xxx 的行的目的是什么?我认为你不需要那些。你可以直接遍历phrase
  • 为什么最后一次打印的 shift 是 95?
  • 当您运行 print(cipher(' !\"#$', 95)) 时,您将所有字符都移到 126 以上。那么您要达到什么目的?
  • @Wyatt x 仅供我打印,以查看我正在寻找的打印输出的原件。 xx 是 .join 所以它不会像 abcde 而不是 ['a','b','c','d','e'] 那样打印出来。我基本上只是在开始时这样做,看看我是否能正确打印出来并且从未删除它们。
  • @gommb 我正在移动 95,因为这是作业的要求。他希望我们遍历密码中的 ascii 索引 32 - 126

标签: python indexing ascii indices caesar-cipher


【解决方案1】:

这应该可以工作(请注意,我清理了您的代码):

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
[' ', '!', '"', '#', '$']
 !"#$

【讨论】:

  • 感谢您的帮助。对此,我真的非常感激。该代码编辑有效。
  • 这不就是和原代码里做cipher(' !"#$', 0)一样吗?
  • @Wyatt 是的,但我认为这只是一个测试,以确保它正确环绕。
【解决方案2】:

我很想找到一个使用模数且范围不是从 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))
# -> (' !"#$', ' !"#$')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2012-12-13
    • 2010-11-05
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多