使用f-string触发SyntaxError:读取names.txt文件遍历名称列表出现无效语法错误求助
Hey there! Let's sort out that syntax error you're hitting.
The Root Cause
The line print(f"hello, {name}") uses an f-string (formatted string literal), which was only introduced in Python 3.6. If you're running an older version of Python (like 3.5 or earlier, or even Python 2), this syntax isn't recognized—hence the SyntaxError you see.
Solutions
1. Upgrade Your Python Version
The simplest fix is to upgrade to Python 3.6 or a newer release. Once you do that, your original code will work exactly as written, since f-strings are fully supported.
2. Use str.format() Instead
If you can't upgrade Python right now, replace the f-string with the older str.format() method, which works in all modern Python versions (including Python 2.7):
Here's the modified code:
names = [] with open("names.txt") as file: for line in file: names.append(line.rstrip().capitalize()) for name in sorted(names, reverse=True): print("hello, {}".format(name))
This does the exact same thing as your original code—just using a syntax that's compatible with older Python versions.
内容的提问来源于stack exchange,提问作者Getu

