python - 如何将反斜杠转义序列放入 f 字符串
问题描述
我想写一些简单的东西
"{}MESSAGE{}".format("\t"*15, "\t"*15)
使用
f"{'\t'*15}MESSAGE{'\t'*15}" # This is incorrect
但我收到以下错误:
>>> something = f"{'\t'*6} Weather"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> something = f"{\'\t\'*6} Weather"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
我怎样才能做到这一点?
解决方案
你可能会看到这个:
>>> f"{'\t'*15}MESSAGE{'\t'*15}"
File "<stdin>", line 1
f"{'\t'*15}MESSAGE{'\t'*15}"
^
SyntaxError: f-string expression part cannot include a backslash
为简单起见,f-string 表达式不能包含反斜杠,所以你必须这样做
>>> spacer = '\t' * 15
>>> f"{spacer}MESSAGE{spacer}"
'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMESSAGE\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'
>>>
推荐阅读
- php - PHP 异步选项
- cassandra - 修复后修复状态不是 100%
- r - 使用 ggplot 同时显示希腊符号和电荷分面标题
- angular - 服务工作者完成获取新文件时触发事件?
- mysql - 警告:#1292 日期时间值不正确
- javascript - 显示未重叠的所有其他元素
- javascript - Fire-base Cloud Function 部署完成且没有任何错误,但 Firebase 中不存在 Cloud Function
- java - Jackson Custom Deserializer,用于多态对象和默认字符串字面量
- javascript - Ag-Grid 触发 onColumnResized 时触发 onDragStopped
- loops - 验证 terraform 中的输入变量列表