代码之家  ›  专栏  ›  技术社区  ›  Python learner Shaavin

在解码过程中保留空间

  •  1
  • Python learner Shaavin  · 技术社区  · 2 年前

    我需要编写一个程序,将编码的信息,翻转过来,删除任何字符,不是一个字母或空格,并输出隐藏的信息。
    示例输入:

    d89%l++5r19o7W *o=l645le9H
    

    预期产出:

    Hello World 
    

    我的输出:

    HelloWorld
    

    H e l l o w o r l d
    

    我的代码:

    decode = [ch for ch in input() if ch.isalpha()]
    print("".join(decode[::-1]))
    
    3 回复  |  直到 2 年前
        1
  •  2
  •   BrokenBenchmark    2 年前

    空格字符不是字母数字字符。

    在原始代码中,使用:

    decode = [ch for ch in input() if ch.isalpha() or ch == ' ']
    

    相反


    如果要保留空格字符以外的其他类型的空格(例如制表符、换行符),请使用:

    decode = [ch for ch in input() if ch.isalpha() or ch.isspace()]
    
        2
  •  1
  •   Tim Biegeleisen    2 年前

    下面是一种正则表达式方法:

    inp = "d89%l++5r19o7W *o=l645le9H"
    output = re.sub(r'[^A-Z ]+', '', inp, flags=re.I)[::-1]
    print(output)  # Hello World
    
        3
  •  1
  •   kennarddh    2 年前
    inp = 'd89%l++5r19o7W *o=l645le9H'
    
    decode = []
    
    for i in inp[::-1].split():
        decode.append("".join([ch for ch in i if ch.isalpha()]))
    
    print(" ".join(decode))