Need syntax help for python caeasar cipher one liner with input from bash echo command

StackOverflow https://stackoverflow.com/questions/22158893

  •  19-10-2022
  •  | 
  •  

Вопрос

I am attempting to write a python one liner for a caeasar cipher the takes input from echo and shifts it 3 characters. when I run it I get a syntax error message. I would appreciate it if someone could point out where I am getting the syntax wrong. I am using python 2.6 on cent os 6.

~ $ echo "HELLO" | python -c "import sys; print ' '.join(chr(ord(line)+3ys.stdin])"

File "", line 1

import sys; print ' '.join(chr(ord(line)+3)[for line in sys.stdin])
                                              ^

SyntaxError: invalid syntax

Of course the out put should print: KHOOR.

Thank you.

Это было полезно?

Решение

The immediate syntax error is because of the square brakets you're putting around for line in sys.stdin. Those are unnecessary and should simply be dropped.

However, you're still going to have an issue with your code, because you're calling ord on a full line, not just a single character. You probably need an additional loop to iterate over the characters of each line. In the following code, that's what I do, with the further addition of stripping the line so that we don't try to shift the newline character to something strange:

import sys; print "\n".join("".join(chr(ord(char)+3) for char in line.strip()) for line in sys.stdin)

Другие советы

I think what you want is

import sys; print ' '.join([chr(ord(line)+3) for line in sys.stdin])
                           ^

Doc for list comprehensions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top