简体   繁体   English

带有格式字符串和对象字面量的 Python SyntaxError

[英]Python SyntaxError with format string and object literal

This code produces SyntaxError :此代码产生SyntaxError

f'something_{{ 'BEAM': '.', 'GRIN': '.', 'GRIN31': '/' }[coin]}'

Is it possible to use object literals this way for an inline "select"?是否可以将对象文字以这种方式用于内联“选择”?

There are two problems.有两个问题。

First, you can't use single quotes in the dict display, because the string parser doesn't consider the braces to "separate" them;首先,不能在dict显示中使用单引号,因为字符串解析器不考虑大括号来“分隔”它们; the first ' closes the string literal.第一个'关闭字符串文字。 (Or rather, you need to use different quotes or escape the quotes to avoid unintentionally closing the f-string.) (或者更确切地说,您需要使用不同的引号或转义引号以避免无意中关闭 f 字符串。)

Second, {{ is a single literal { in an f-string;其次, {{是 f 字符串中的单个文字{ you need to separate them with a space.你需要用空格将它们分开。

>>> coin = "GRIN"
>>> f'something_{ { "BEAM": ".", "GRIN": ".", "GRIN31": "/" }[coin]}'
'something_.'

Yes, it's possible, here a example:是的,这是可能的,这里有一个例子:

$ test1 = 'abc'
$ test2 = '123'
$ test3= 'foo'
$ coin = 'foo'
f"something_{ { test1: '.', test2: '.', test3: '/' }[coin]}"
>>> something_/

on f-string syntax, the brackets is represents by double {{ or }} => { or }, that's why first 2 { has an empty space between them.在 f-string 语法中,方括号由 double {{ or }} => { or } 表示,这就是为什么第一个 2 { 在它们之间有一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM