简体   繁体   中英

Invalid Python Syntax Error

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.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM