有没有办法在fstring中包含注释?

2024-04-26 04:57:36 发布

您现在位置:Python中文网/ 问答频道 /正文

mo在f字符串中包含注释是很有用的。例如,以以下代码为例:

f"""
<a
   href="{ escape(url) }"
   target="_blank" { # users expect link to open in new tab }
>bla</a>
"""

如果此代码等效于:

f"""
<a
   href="{ escape(url) }"
   target="_blank" 
>bla</a>
"""

可以在花括号之间包含完整的Python表达式,但看起来不能包含注释。我说得对吗?有办法做到这一点吗


Tags: to字符串代码inurltargetlinkopen
3条回答

您不能在表达式中写入注释。但您可以在多个片段中编写字符串,并在两个片段之间编写注释,前提是下一个片段从不同的行开始:

s = (f"""
<a
   href="{ escape(url) }"
   target="_blank" """ # users expect link to open in new tab
f""">bla</a>
""")

否。f字符串中没有注释

在构建str时,模板引擎可能会过度使用。加入strlist可能是可取的

s = ''.join([
    '<a',
    f' href="{escape(url)}"',
    ' target="_blank">',
    # users expect link to open in new tab
    'bla</a>',
])

PEP498

Comments, using the '#' character, are not allowed inside an expression.

除了在Python中放置'#'字符之外,没有其他方法进行注释,因此这是不可能的

相关问题 更多 >