使用文字字符串插值或 f 字符串时出现 SyntaxError [英] SyntaxError when using literal string interpolation or f-strings

查看:37
本文介绍了使用文字字符串插值或 f 字符串时出现 SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 with open('C:\test.csv') 作为 csvfile:csv_reader = csv.reader(csvfile, delimiter=',')行数 = 0对于 csv_reader 中的行:如果 line_count == 0:打印(f'列名是{", ".join(row[0])}')行数 += 1别的:print(f'\t{row[0]} 在 {row[2]} 的 {row[1]} 部门工作.')

我收到以下错误:

SyntaxError: 无效语法PS C:\users\XXX\documents\python>蟒蛇读CSV.py文件ReadCSV.py",第 12 行打印(f'列名是{", ".join(row[0])}')^语法错误:无效语法

解决方案

文字字符串插值或f-strings"仅在 Python3.6 中引入.
看:

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

$ python3.6 -V蟒蛇 3.6.7$ python3.6 readcsv.py列名是 c, o, l, 11 在 3 的 2 部门工作.4 个在 6 个部门的 5 个部门工作.

<小时>

$ python3 -V蟒蛇 3.5.2$ python3 readcsv.py文件readcsv.py",第 9 行打印(f'列名是{", ".join(row[0])}')^语法错误:无效语法

<小时>

$ python -V蟒蛇 2.7.12$ python readcsv.py文件readcsv.py",第 9 行打印(f'列名是{", ".join(row[0])}')^语法错误:无效语法

Trying to read a csv file and print contents:

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]}.')

I received following error:

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

解决方案

Literal String Interpolation or "f-strings" was only introduced in Python3.6.
See: https://www.python.org/dev/peps/pep-0498/

Your code works fine on Python3.6.
If you are not using Python3.6 (and up), you will get a syntax error.

$ 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

这篇关于使用文字字符串插值或 f 字符串时出现 SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆