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

Python中如何为字符串添加引号?f-string输出场景的实现问题

原代码问题原因

你原来的写法只是把message变量的内容直接插入到输出字符串中,没有给它的外侧包裹引号字符,所以输出不会自带引号。同时你期望的输出中句号在引号外侧,还需要调整原message末尾自带的句号位置。

修正方案

要实现你需要的输出效果,有两种常用的简单写法:

first_name = "albert"
last_name = "einstein"
message = "A person who never made a mistake never tried anything new."

# 写法1:单双引号嵌套(无需转义,可读性更高)
print(f'{first_name.title()} {last_name.title()} once said, "{message.rstrip(".")}" .')

# 写法2:转义双引号实现
print(f"{first_name.title()} {last_name.title()} once said, \"{message.rstrip('.')}\" .")

代码说明

  • Python支持单双引号嵌套使用,当f-string外层用单引号包裹时,内层的双引号会被识别为普通输出字符,不需要额外转义
  • rstrip(".")方法的作用是移除message变量末尾自带的句号,从而把句号放在引号外侧,完全匹配你期望的输出格式
  • 如果你不需要调整句号位置,只需要给message外层加引号,直接在变量占位符两侧加引号即可:
# 无需调整句号位置的写法
print(f'{first_name.title()} {last_name.title()} once said, "{message}"')
# 输出:Albert Einstein once said, "A person who never made a mistake never tried anything new."

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:06:03