Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

I think what you want is

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

Doc for list comprehensions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top