如果必须转义f-字符串中的花括号,则可以将其加倍,因此{{hello}}
将导致{hello}
。问题是,算法只是将字符串连接起来,然后将这个部分解释为每一个其他部分。因此,如果该字符串中存在任何结构,则触发一些f-字符串行为,它将失败。
例如,如果您想插入一个具有如下所示的RegExp的字符串
_date = f'''
SELECT
acol,
substring(full_date , '[0-9]{{4}}')
FROM
dates
'''
它的结果是期望的结果。F-字符串立即被转换,因此模式更改为
substring(full_date , '[0-9]{4}')
根据SQL查询的需要。
但是这个字符串作为
_date.format(acol=acol)
若要插入acol变量,请执行以下操作失败:
IndexError: Replacement index 4 out of range for positional args tuple
因为{4}
总是被解释为替换的索引。以何种方式插入{4}
并不重要。因为这对格式算法没有影响。
是否有任何解决方案,例如阻止格式算法解释这个字符串部分?
发布于 2022-08-10 12:49:50
除非您还没有提到更多的约束,否则这根本不需要是f字符串:
_date = '''
SELECT
{acol},
substring(full_date , '[0-9]{{4}}')
FROM
dates
'''
formatted = _date.format(acol="some_col")
print(formatted)
版画
SELECT
some_col,
substring(full_date , '[0-9]{4}')
FROM
dates
https://stackoverflow.com/questions/73304877
复制相似问题