python - 转义 f 字符串中的字符
问题描述
我遇到了以下问题f-string
:
>>> a='hello'
# how to print '{hello}' ?
>>> f'{{a}}'
'{a}'
>>> f'\{{a}\}'
File "<stdin>", line 1
SyntaxError: f-string: single '}' is not allowed
# doing it without f-strings
>>> '{' + a + '}'
'{hello}'
如何在 fstring 中转义字符?
解决方案
你需要三重括号:
f'{{{a}}}'
两个外部{}
s “转义”并评估为{...}
,然后内部{}
用于格式化(或者至少我是这样解释的)。
推荐阅读
- python - 如何计算文件中某行中某个单词的出现次数
- matlab - MATLAB/嵌入式编码器文件加载
- google-app-engine - blobstore.create_gs_key 的反面是什么
- php - gmdate('U') 根据项目给出不同的结果
- java - 使用 Resttemplate 的多个异步 HTTP 请求
- merge - 如何合并两个数据集以便日期合并为一列而所有其他列保留?
- ansible - Ansible 从列表中获取第一个元素
- scala - 合并错误猫已验证
- python - 加载单个页面 - Django REST 框架中的权限
- html - 缩小屏幕尺寸时将一个 jumbotron 堆叠在一起