Python中如何让插入字符串的变量使用双引号而非单引号?
解决Python列表插入字符串时显示双引号的问题
在Python中使用format()或f-string将字符串列表插入其他字符串时,列表默认会以单引号包裹元素的形式输出:
arr = ["foo"] print(f"Ahhh I need double quotes here: {arr}")
运行后输出:
Ahhh I need double quotes here: ['foo']
如果想要输出带双引号的格式:
Ahhh I need double quotes here: ["foo"]
可以用以下几种无需复杂正则的方法实现:
手动构造格式化字符串
通过str.join()拼接列表元素,再手动添加双引号包裹的结构:arr = ["foo"] formatted_list = f'["{", ".join(arr)}"]' print(f"Ahhh I need double quotes here: {formatted_list}")这种方式适合元素简单的场景,多个元素时也能自动用
,分隔。利用JSON序列化
JSON格式的字符串默认使用双引号,直接用json.dumps()将列表转为符合要求的字符串:import json arr = ["foo"] print(f"Ahhh I need double quotes here: {json.dumps(arr)}")这个方法兼容性强,即使列表包含特殊字符或多个元素,也能正确生成双引号格式。
简单替换单引号
将列表转为字符串后,直接替换单引号为双引号:arr = ["foo"] print(f"Ahhh I need double quotes here: {str(arr).replace(\"'\", '\"')}")或者调整引号嵌套避免转义:
arr = ["foo"] print(f'Ahhh I need double quotes here: {str(arr).replace("\'", "\"")}')
内容的提问来源于stack exchange,提问作者Nic Szerman
相关产品推荐
相关产品推荐

