python-3.x - Python3 f 字符串 : how to avoid having to escape literal curly brackets?

标签 python-3.x escaping f-string

有没有办法避免在 python3 f-string 中转义文字大括号字符?
例如,如果你想输出一个 json 字符串或一大块 CSS 规则,如果你想使用 f-string 语法,必须将所有 {} 字符转换为 {{}} 真的很不方便。
我知道可以使用旧的语法,例如div {color: %s} % color'text {}'.format(abc)string templates 但我想知道是否有一种方法可以在原始文本上使用 f 字符串,最好是通过某种方式来标记“原始”块的开头和结尾,使用某种分隔符,例如类似于如何使用 \Q\E in a java regex 在正则表达式中包含未转义的原始字符。
作为替代方案,标准库中是否有允许获取一大块原始文本并将其转换为 f 字符串安全格式的内容? (同样,类似于如何将 Pattern.quote 用于 Java 正则表达式)

最佳答案

一个可以用implicit string concatenation仅将 f 字符串格式应用于字符串的一部分。

[...] Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals.


>>> hello = "world"
>>> "{hello}" f"{hello}" "!"
'{hello}world!'
这使用与带有转义符的相应 f 字符串完全相同的字节码。
请注意,空格是可选的,但有助于提高可读性。

关于python-3.x - Python3 f 字符串 : how to avoid having to escape literal curly brackets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315003/

相关文章:

python - "esc"键盘键本身的 VT100 转义码是什么

python - 我可以将 Python 3.6 的格式化字符串文字(f-strings)导入旧的 3.x、2.x Python 吗?

java - 查询反斜杠字符

python - 在 Python3 中使用 %x 格式化不好吗?

python - 使用 f 字符串打印生成

python-3.x - 在python中拆分具有多个值的列

python - 有没有办法制作多人骰子游戏,让玩家轮流掷骰子并计算分数?

python - split() 函数是否更改

python - groupby 上的“值的长度与索引的长度不匹配”

python - 如何阻止 BeautifulSoup 转义内联 javascript