使用文字字符串插值或f字符串时出现SyntaxError

时间:2019-02-11 23:32:25

标签: python python-3.x syntax-error f-string

尝试读取csv文件并打印内容:

with open('C:\test.csv') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row[0])}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department in {row[2]}.')

我收到以下错误:

SyntaxError: invalid syntax
PS C:\users\XXX\documents\python> python ReadCSV.py
  File "ReadCSV.py", line 12
    print(f'Column names are {", ".join(row[0])}')
                                            ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:1)

仅在Python3.6中引入了文字字符串插值或“ f-strings”。
看到: https://www.python.org/dev/peps/pep-0498/

PEP498

您的代码在Python3.6上运行良好。
如果您不使用Python3.6(及更高版本),则会收到语法错误。

$ python3.6 -V
Python 3.6.7
$ python3.6 readcsv.py 
Column names are c, o, l, 1
        1 works in the 2 department in 3.
        4 works in the 5 department in 6.

$ python3 -V
Python 3.5.2
$ python3 readcsv.py 
  File "readcsv.py", line 9
    print(f'Column names are {", ".join(row[0])}')
                                                ^
SyntaxError: invalid syntax

$ python -V
Python 2.7.12
$ python readcsv.py 
  File "readcsv.py", line 9
    print(f'Column names are {", ".join(row[0])}')
                                                ^
SyntaxError: invalid syntax