简体   繁体   中英

f-strings giving SyntaxError: invalid syntax?

I'm trying to learn Python and I'm getting a syntax error message in Sublime Text while trying to run this f-string code

Code:

 # print welcome message
 greeting = 'Hello'
 name = 'Michael'
 message = f'{greeting}, {name}. Welcome!'
 
 print(message)

Error:

SyntaxError: invalid syntax
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/stevie/Desktop/intro.py"]
[dir: /Users/stevie/Desktop]

I find myself having the same issue even though I am using Python 3.7.3

This is what I can add to the discussion... when I run same from the command line (invoking the same .py file as created in SublimText) it runs as expected without error.

But it appears that SublimeText cannot deal with the f-strings even though it treats it like a proper command when being entered. Only gives "Invalid Syntax" when running (with Tools-->Build).

Obviously a newbie myself. I'll keep doing some research but wanted to point out how it runs properly from command line. Examples of my experience below. Thanks in advance for any input.

This is my (cough, cough)... code.

greeting = 'Hello'
name = 'Vato'

# message = greeting + ", " + name + "! Welcome.
# message = "{}, {}! Welcome.".format(greeting, name)                  
# f"{'Eric Idle'}"

message = f'{greeting}, {name}! Welcome.'

print('')
print(message)
print('')

This is the hassle that I get from the interpreter using SublimeText (Tools-->Build).

  File "/Users/AAvalos/PythonArea/Intro.py", line 9
    message = f'{greeting}, {name}! Welcome.'
                                            ^
SyntaxError: invalid syntax
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/AAvalos/PythonArea/Intro.py"]
[dir: /Users/AAvalos/PythonArea]
[path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/AAvalos/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware Fusion.app/Contents/Public]

But runs just fine from the command line.

~/ 03:31:16$
~/ 03:31:37$
~/ 03:31:37$python PythonArea/Intro.py 

Hello, Vato! Welcome.

~/ 03:31:38$
~/ 03:31:39$

You can always switch to .format() :

# print welcome message
greeting = 'Hello'
name = 'Michael'
message = '{}, {}. Welcome!'.format(greeting, name)

print(message)
Hello, Michael. Welcome!
greeting = 'Hello'
name = 'Michael'
message = f'{greeting} {name} !'
print(message)

//This will work fine//

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