0

Inside the shell, I get the following response when I try to import my program.

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "tweet.py", line 26
        print "Favorited: %s" % (result['text'])
                            ^
SyntaxError: invalid syntax

Why does print "Favorited: %s" % (result['text']) return an error? Googling has been unhelpful, this was working for me earlier...

Update, I'm running the following version of Python:

Python 2.7.5 |Anaconda 1.6.1 (x86_64)| (default, Jun 28 2013, 22:20:13) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

Update again, here is the function:

def fetch_tweet(tweet):
    try:
        result = t.favorites.create(_id=tweet['id'])
        print "Favorited: %s" % (result['text'])
        return result
    # when you have already favourited a tweet, this error is thrown
    except TwitterHTTPError as e:
        print "Error: ", e
        return None

Update #3 - found the error!

Turns out my python interpreter really hated a bit of code I had at the top, which was messing with print somehow - I deleted from __future__ import print_function from the top of the file and everything started working smoothly.

9
  • 1
    What Python version are you using? Commented Nov 23, 2013 at 5:46
  • Updated with information above... Commented Nov 23, 2013 at 5:48
  • 1
    It might simply be an indentation issue. Try to reduce it to the simplest program that reproduces the problem, and re-post with the entire code. I'm sure you'll get helpful answers. Commented Nov 23, 2013 at 5:48
  • Could you post a bit more code? Commented Nov 23, 2013 at 5:49
  • 1
    Try to run this code separate from the rest of your program. If that code works, the problem is not your Python installation, at least. Commented Nov 23, 2013 at 6:02

1 Answer 1

2

I see you got it working, but here's the explanation:

Python 3 changed how printing works for various reasons. The big change is that print is now a function instead of a statement (this is helpful because it allows you to, say, pass parameters to it if you want to change things like where it prints to, whether to terminate with a newline, etc)

So when you had the line:

from __future__ import print_function

It was using Python 3 printing, but you're running in Python 2. One solution (as you found) is to remove the import, but you could also change the print statement to a function. For simple statements like this you just need to add parens, so this would have worked:

print("Favorited: %s" % (result['text']))

These would also work:

print("Favorited: {}".format(result['text']))

print("Favorited:", result['text'])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.