You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python的f-string是否有等价于C++ std::quoted的内置功能?

Python f-string是否有等价于C++ std::quoted的内置实现?

问题背景

在C++中,std::quoted流操纵器可以生成字符串的带引号转义版本,示例如下:

std::string dirPath = "C:\\Documents\\Oval Office Recordings\\Launch Codes.txt";

std::cout << dirPath << endl; // C:\Documents\Oval Office Recordings\Launch Codes.txt

std::cout << std::quoted(dirPath) << endl; // "C:\\Documents\\Oval Office Recordings\\Launch Codes.txt"

请问Python的f-string是否有直接等价于std::quoted的原生内置实现?这里的“直接”指无需自行编写逻辑,仅使用Python原生功能。(背景:需要移植一个用到std::quoted的C++奎因程序,希望改动尽可能少)


回答

Python标准库中没有可以直接嵌入f-string、完全等价于C++ std::quoted的内置操纵器,但有两个原生方法可以实现类似的带引号转义效果:

1. 使用repr()函数

repr()是Python内置函数,返回对象的官方字符串表示。对于字符串,它会自动添加引号(单/双引号根据内容自动选择)并转义特殊字符:

dir_path = r"C:\Documents\Oval Office Recordings\Launch Codes.txt"
print(dir_path)  # 输出:C:\Documents\Oval Office Recordings\Launch Codes.txt
print(repr(dir_path))  # 输出:'C:\\Documents\\Oval Office Recordings\\Launch Codes.txt'

如果需要强制使用双引号(和std::quoted输出一致),可以结合字符串替换嵌入f-string:

print(f"{repr(dir_path).replace('"', '\\"').replace("'", '"')}")
# 输出:"C:\\Documents\\Oval Office Recordings\\Launch Codes.txt"

优点:无需导入任何模块,适合奎因程序这类对代码简洁性要求高的场景。

2. 使用json.dumps()函数

来自标准库json模块的dumps()函数,可以生成符合JSON格式的带双引号转义字符串,输出风格和std::quoted几乎完全一致:

import json
dir_path = r"C:\Documents\Oval Office Recordings\Launch Codes.txt"
print(json.dumps(dir_path))  # 输出:"C:\\Documents\\Oval Office Recordings\\Launch Codes.txt"

也可以直接嵌入f-string:

print(f"{json.dumps(dir_path)}")

优点:输出格式完全匹配std::quoted的双引号转义效果,无需额外处理引号类型。


内容的提问来源于stack exchange,提问作者templatetypedef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:23:24