Home > database >  Retaining spaces in decoding process
Retaining spaces in decoding process

Time:04-11

I need to write a program that will take the encoded message, flip it around, remove any characters that are not a letter or a space, and output the hidden message.
Sample input:

d89%l  5r19o7W *o=l645le9H

Expected output:

Hello World 

My output:

HelloWorld

If I use a white space as separator, it returns

H e l l o w o r l d

My code:

decode = [ch for ch in input() if ch.isalpha()]
print("".join(decode[::-1]))

CodePudding user response:

The space character is not an alphanumeric character.

In your original code, use:

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

instead.


If you want to retain other types of whitespace besides the space character (e.g. tabs, newlines), use:

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

CodePudding user response:

Here is a regex approach:

inp = "d89%l  5r19o7W *o=l645le9H"
output = re.sub(r'[^A-Z ] ', '', inp, flags=re.I)[::-1]
print(output)  # Hello World

CodePudding user response:

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))
  • Related