-1

Formatted string literals in Python 3.6+

I was reading into formatted string literals (a.k.a f-string) which is a feature added from the Python 3.6 update. I find it easier to read then the previous ways to doing similar projects, but I am having trouble executing the code. Here an example (test.py) of what I made so far:

#!/usr/bin/python3

greeting = 'Hello'
name = 'World'

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

print(message)

As you can see, it is simple code I used to get more familiar with this f-string feature. When I try to run this code I keep getting this error:

File "/home/user/Desktop/Python/My Programs/test.py", line 5
    message = f'{greeting}, {name}.'
                                   ^
SyntaxError: invalid syntax
[Finished in 0.0s with exit code 1]

Now this error response is telling me that the final ( ' ) is what is causing this not to run correctly. I have tried to space it differently to see if it could be as simple as that, but still no luck. Here is a look into my setup that I use to write and execute Python code:

Text Editor:

I am currently using Sublime Text with features added to help code Python3 code. These features include: BracketHighlighter and Anaconda packages. I have also changed some settings within Sublime Text, but I don't believe that is causing this issue because I mainly only changed graphical features.

Extras:

At first I thought Sublime Text might be trying to execute the Python3 code with a lower version of Python, so when I tried to execute it via Terminal in Ubuntu, it still gave me the same error. I executed the code with this:

python3 test.py

Hopefully this is enough information to where someone can spot out the issue. I really want to wrap my head around these f-strings so any help is greatly appreciated.

TazerFace
  • 170
  • 12

1 Answers1

1

Due to the requests, I have double checked the current version of Python I have using:

import sys; print(sys.version)

Which replied with the following response:

3.6.1 (default, Mar 22 2017, 06:17:05) 
[GCC 6.3.0 20170321]

Solution for code:

What seemed to solve my problem was adding this to the terminal command to execute it:

python3.6 test.py

before I had only:

python3 test.py

That was only using Python3.5.x to execute it. Now when I use the python3.6, everything runs like it should.

Solution for Sublime Text:

Also for Sublime Text, I found out that it was the 'Build System' that was set on it's factory Python version (3.5.x), however I made a new Build System with the following code:

{
    "cmd": ["/usr/bin/python3.6", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

Once I saved this file and selected it, I was able to build the code within Sublime with no problem as well.

TazerFace
  • 170
  • 12