【问题标题】:I don't understand why using " " in my code works, but the same code with ' ' does not我不明白为什么在我的代码中使用 " " 有效,但带有 ' ' 的相同代码却不行
【发布时间】:2020-09-08 21:22:47
【问题描述】:

这是我正在使用的代码:

with open(os.path.join(my_path, 'pastimes.csv'), 'r') as my_file:
    my_file_reader = csv.DictReader(my_file)
    line_count = 0
    for row in my_file_reader:
        if line_count == 0:
            print(f'Column names are {', '.join(row)}')
            line_count += 1
        print(f'{row['Person']} has a favourite pastime of {row['Favourite Pastime']}.')
        line_count += 1

上面的不起作用,但下面的起作用:

with open(os.path.join(my_path, 'pastimes.csv'), mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'{row["Person"]} has a favourite pastime of {row["Favourite Pastime"]}.')
        line_count += 1

我就是不知道为什么!

【问题讨论】:

  • 你应该使用更好的IDE,或者至少提供词法高亮,或者更好的语法高亮甚至语义高亮的编程文本编辑器。即使是 Stack Overflow 上极其简单和蹩脚的词汇突出显示也已经清楚地显示了您问题中的差异。
  • @JörgWMittag 这是一个好点。我会把它带上船:)

标签: python-3.x csv dictionary


【解决方案1】:
f'Column names are {', '.join(row)}'

在上面的语句中,'Col ... {' 这是一个字符串,但在

f'Column names are {", ".join(row)}'

现在'Col...}'字符串

这是因为字符串在 ' 对之间,而您的对在实际字符串结束之前关闭字符串。

你也可以使用以下

f'Column names are {\', \'.join(row)}'

【讨论】:

  • 太棒了。我为此头疼了一个小时。非常感谢!
  • @Chadmeistr - 这也被称为“引用地狱”,特别是如果您需要处理两个以上嵌套的 " ' \" \' \\\" \\\' \\\\\" 引号
  • @slebetman 看起来确实像地狱。我会在某个时候解决它:D
  • 如果你得到了答案,请考虑接受它。
  • @Chadmeistr 是的,大多数语言并没有真正解决这个问题,但我喜欢 Tcl 如何通过使用 {} 作为字符串引号来回避这个问题,这允许在里面嵌套字符串字符串。 整洁 的解决方案是 Perl 可以让您使用 qqqw 运算符选择自己的字符串引号:qq[this is a string]qq|this is also a string|
猜你喜欢
  • 2023-04-01
  • 2022-08-08
  • 1970-01-01
  • 2015-05-05
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
相关资源
最近更新 更多