Python3 f-strings:如何避免转义文字大括号?

Python3 f-strings: how to avoid having to escape literal curly brackets?

有没有办法避免在 python3 f-string 中转义文字大括号字符?

例如,如果你想输出一个 json 字符串或一大块 CSS 规则,那么必须转换所有 {} 字符真的很不方便到 {{}} 以防您想使用 f-string 语法。

我知道可以使用较旧的语法,例如div {color: %s} % color'text {}'.format(abc)string templates but I wonder if there is a way to use the f-strings on raw text, preferably by having a way to mark the beginning and end of the 'raw' blocks with some kind of delimiter, for example similar to how you can use \Q and \E 以便在正则表达式中包含未转义的原始字符。

作为替代方案,标准库中是否有允许获取大量原始文本并将其转换为 f-string-safe 格式的内容? (同样,类似于如何将 Pattern.quote 用于 java 正则表达式)

python 中有三种操作字符串的方法。

  1. 使用 f 字符串
  2. 使用 str.format 表达式
  3. %-格式化表达式

请参考this link

如果需要,您可以创建自己的自定义函数并调用它。

def format_string(data,template):
    for key, value in data.items():
    return template.replace("#%s#" % key, str(value))
    
    
template ="<html><body>name is :#name# , profession is :#profession#<body></html>"
data ={"name":"Jack","profession":"student"}    
format_string(data,template)

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

[...] 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-string 完全相同的字节码。 请注意,空格是可选的,但有助于提高可读性。