【问题标题】:Making a decryption program in python用python制作解密程序
【发布时间】:2013-02-05 09:08:07
【问题描述】:

所以不久前,我寻求有关加密程序的帮助,
你们太棒了,想出了解决方案。
所以我再次来找你寻求等效解密程序的帮助。 我目前得到的代码是这样的:

whinger = 0
bewds = raw_input ('Please enter the encrypted message: ')
bewds = bewds.replace(' ', ', ')
warble = [bewds]
print warble
wetler = len(warble)
warble.reverse();
while whinger < wetler:
    print chr(warble[whinger]),
    whinger += 1

但是当我输入
101 103 97 115 115 101 109
它出现了输入不是整数的错误。
我需要的是,当我输入数字时,它会将它们变成整数列表。
但我不想单独输入所有数字。

提前感谢您的帮助:P

【问题讨论】:

    标签: python encryption


    【解决方案1】:

    将输入字符串转换为整数列表:

    numbers = [int(s) for s in "101 103 97 115 115 101 109".split()]
    

    【讨论】:

    • 他也在添加','。所以他可能需要做一个split(', ') 或者停止添加逗号。
    • @aychedee: 如果逗号后面没有空格,split(", ") 将不起作用,并且它不会拆分由空格分隔的整数。 @martineau's answerreplace(",", " ").split() 可用于支持空格和逗号。虽然为了简单起见,我将有效输入限制为空格。
    • 是的,但他明确地将空格替换为, 。 (逗号,空格)所以:-P
    【解决方案2】:

    这几乎是我能想到的最简单的方法:

    s = '101 103 97 115 115 101 109'
    numbers = []
    for number_str in s.replace(',', ' ').split():
        numbers.append(int(number_str))
    

    它将允许用逗号和/或一个或多个空格字符分隔数字。如果您只想允许空格,请忽略“.replace(',', ' ')”。

    【讨论】:

      【解决方案3】:

      您的问题是, raw_input 返回一个字符串给您。所以你有两个选择。

      1、使用正则表达式库re。例如:

      import re
      bewds = raw_input ('Please enter the encrypted message: ')
      some_list = []
      for find in re.finditer("\d+", bewds):
          some_list.append(find.group(0))
      

      2,或者您可以使用该问题投票最多的答案中描述的拆分方法:sscanf in Python

      【讨论】:

      • 当然,这就是我提到它的原因 :-) 但是问人显然是 python 中的新手,所以有更多的选择,如何做到这一点,不会造成任何伤害 :-)
      • 恕我直言,应该先向新人展示最简单的方法。
      【解决方案4】:

      你也可以使用map

      numbers = map(int, '101 103 97 115 115 101 109'.split())
      

      这在 Python 2 中返回一个列表,但在 Python 3 中返回一个 map 对象,您可能希望将其转换为列表。

      numbers = list(map(int, '101 103 97 115 115 101 109'.split()))
      

      这和J. F. Sebastian's answer.完全一样

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-18
        • 2020-03-27
        相关资源
        最近更新 更多