4

I am trying to input a string using echo into a Python one liner then perform a Caeasar's Cipher on the string.

One of the examples my instructor gave me was this.

~ $ echo "Hello Holly." | python -c "import sys; [print(line) for line in sys.stdin]"

The output is suppose to be: Hello Holly.

How ever when I type the command in I get:

File "<string>", line 1
 import sys; [print(line) for line in sys.stdin]
                  ^
SyntaxError: invalid syntax

I would appreciate it if someone could point out the error to me. I am using Python 2.6 on Centos 6.

Thanks.

1
  • 1
    Using list comprehensions simply to apply a function to each item in a list without caring about the resulting list is a bad habit to get into; shame on your instructor. Use ... | python -c 'import sys; print "".join(sys.stdin)' instead. Commented Mar 3, 2014 at 18:15

2 Answers 2

6

In Python 2 print is a statement, not a function. Try this instead:

echo "Hello Holly." | python -c "import sys; print [line for line in sys.stdin]"

Alternatively, you could use the following to just print plain text (thanks @mgilson):

echo "Hello Holly." | python -c "import sys; print ' '.join([line for line in sys.stdin])"
Sign up to request clarification or add additional context in comments.

8 Comments

Just to elaborate, using Python 3, OP's implementation will work :)
Looks OK now, but you're printing a list, not plain text as OP wants. The cleanest is to probably ' '.join it or something...
@JustinC -- That's not always the case... it depends on how you compile, etc.
bob@pbx:~ $ echo "Hello Holly." | python -c " import sys; print [line for line in sys.stdin]" File "<string>", line 1 import sys; print [line for line in sys.stdin] ^ IndentationError: unexpected indent
@user3375720 make sure you copy and paste directly. It works fine for me using Python 2.6 on CentOS 6. It looks like you have a space between the " following python -c and import - that's probably what's causing the IndentationError.
|
0

It looks like you are using python2 while your isntructor is using python 3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.