【问题标题】:PYTHON basic ascii encryption functionPYTHON基本ascii加密功能
【发布时间】:2017-08-30 09:05:34
【问题描述】:

text 作为输入字符串,rule 作为输入整数时,挑战是找到 ASCII 值总和,然后根据新的数值转换回字符串。

我的代码出现在正确的轨道上,但是给定ascii_encrypt("a",1),例如,我当前的输出是b'b',而它应该是'b'。我是编码功能的新手,我猜这会让我绊倒。

def ascii_encrypt(text, rule):
    text = sum([ord(c) for c in text])
    if not text:
        return ""
    else:
        encrypted_text = chr(text + rule)
        return encrypted_text.encode('utf-8')

【问题讨论】:

  • 你为什么用 UTF-8 编码结果?
  • 一个测试用例有混合字母,所以我认为这可以解决这个问题
  • 我不明白这条线有什么用:text = sum([ord(c) for c in text])。您想将此函数用于大于 1 个字符的字符串吗?

标签: python utf-8 ascii encode


【解决方案1】:

只需删除 .encode('utf-8')。您不需要对其进行编码,它会导致您的问题。您无法包含此部分并实现所需的功能。

def ascii_encrypt(text, rule):
    text = sum([ord(c) for c in text])
    if not text:
        return ""
    else:
        encrypted_text = chr(text + rule)
        return encrypted_text

print(ascii_encrypt("a",1))

【讨论】:

  • 如果我不想打印,而是只返回值而不编码呢?
  • 没错,您不需要打印或编码。将字符串作为字节字符串发送不是一个好主意。只需保留未编码的字符串即可。如果您可以标记为解决方案,那将有很大帮助。
  • 这是我用上面的代码得到的(减去打印功能):UnicodeEncodeError: 'ascii' codec can't encode character '\u0693' in position 11: ordinal not in range(128)
  • @Mr.Jibz 上面代码中的哪一行导致了 UnicodeEncodeError?即使您仍在使用 Python 2,我也看不到这种情况发生。(如果您是:现在是时候切换了!)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2017-11-12
相关资源
最近更新 更多