0

Why does this line give error in bash script?

$ python -c "print "{:02d}".format(3)"

  File "<string>", line 1
    print {:02d}.format(3)
       ^
SyntaxError: invalid syntax

I am typing this directly in terminal.

While in python console :

>>> print "{:02d}".format(1)
01
4
  • You can't "nest" double quotes like that. The inner two quotes aren't getting passed to python they are getting paired with the first and last quote by the shell and being removed so python sees print {:02d}.format(3) as the code to run. Commented Nov 19, 2015 at 4:22
  • Oops. Ah! yes. They are getting paired. Stupid me! thanks for pointing @EtanReisner. :) Commented Nov 19, 2015 at 4:24
  • @AbhishekTripathi feel free to click the tick near any answer below that comes close to answering the question. A proven history of accepting answers on StackOverflow will encourage more people to answer your subsequent questions. Commented Nov 19, 2015 at 4:31
  • @ChrisGuest : I had upvoted other questions when I asked this one. So, when I went clicking on the tick mark, it said 'wait for 8 min'. And then I went busy with something else. Thanks for reminding. ^_^ Commented Nov 20, 2015 at 0:59

1 Answer 1

3

You are using double quotes in bash and attempting to use double quotes in Python too. However it appears that bash is interpreting that as two sets of double quotes without any nesting and they are stripped out and they do not reach the python interpreter. So python sees this and raises a SyntaxError:

print {:02d}.format(3)

Try using single quotes in bash, and double in python. That will be simpler than having to escape the double quotes.

python -c 'print "{:02d}".format(3)'
Sign up to request clarification or add additional context in comments.

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.