f-strings在Python IDLE可用但Sublime报错,求切换Python3方法
Hey there! I totally get where you're coming from—f-strings are such a handy feature, and it's frustrating when your code works in one place but breaks in another. The root of your problem is exactly what you suspected: Sublime Text was still using Python2, which doesn't support f-strings (those were introduced in Python3.6+). Let's walk through how to fix this step by step.
Step 1: Find Your Python3 Executable Path
First, we need to make sure we're pointing Sublime to the correct Python3 installation.
- On Mac/Linux: Open your terminal and run
which python3(orwhich python3.7if you need that specific version). You'll get an absolute path like/usr/bin/python3or/usr/local/bin/python3.7. - On Windows: Open Command Prompt and run
where python3(or check your Python installation directory—usually something likeC:\Python37\python.exe).
Copy this path down, we'll need it in the next step.
Step 2: Create a Custom Python3 Build System
Sublime Text uses "build systems" to run code, so we'll create one specifically for Python3:
- Open Sublime Text, go to
Tools > Build System > New Build System. - Delete the default template text and replace it with this (replace the path with the one you copied earlier):
For Mac/Linux:
{ "cmd": ["/usr/bin/python3", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "env": {"PYTHONIOENCODING": "utf-8"} }
For Windows:
{ "cmd": ["C:\\Python37\\python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "env": {"PYTHONIOENCODING": "utf-8"} }
- Save the file as
Python3.sublime-build—Sublime should automatically prompt you to save it in thePackages/Userdirectory, which is exactly where we want it.
Step 3: Switch to Your New Build System
Now tell Sublime to use this new build system:
- Go to
Tools > Build Systemand select thePython3option you just created. - Open your Python file with the f-string code, press
Ctrl+B(Windows/Linux) orCmd+B(Mac) to run it.
Verify It's Working
To double-check, you can run a quick test code:
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name)
This should now output ada lovelace without any syntax errors.
If it still doesn't work, double-check that your Python3 path is correct in the build system file—sometimes the path can vary depending on how you installed Python. You can also try restarting Sublime Text to make sure the new build system is loaded properly.
内容的提问来源于stack exchange,提问作者David Jiang

