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

如何将含转义序列的字符串转换为格式化字符串并存储?

处理含转义序列的字符串,让转义生效并存储

我从一个函数得到的输出字符串包含转义序列(主要是\n),需要在将其传递给另一个函数前让转义序列生效,把字符串转换成格式化后的形式并存储到变量中(而非仅通过print输出)。示例如下:

text = r'Your team should include the following \nboard-certified experts:\n \nA pulmonologist is a doctor who\'s an \nexpert of lung diseases.\n'

formatted_text = """Your team should include the following 
board-certified experts:
 
A pulmonologist is a doctor who's an 
expert of lung diseases."""

解决方法

方法一:使用encode().decode('unicode_escape')

这是最直接的方式,能快速将字符串中的转义序列转换为实际的控制字符:

text = r'Your team should include the following \nboard-certified experts:\n \nA pulmonologist is a doctor who\'s an \nexpert of lung diseases.\n'
formatted_text = text.encode().decode('unicode_escape')

执行后,formatted_text变量存储的就是处理后的换行形式字符串,在Notebook单元格中直接查看变量时,转义序列会被实际解析,不会保留原形式。

方法二:使用ast.literal_eval(Python 3.10+)

如果你的Python版本在3.10及以上,可以结合str.removeprefix和ast.literal_eval来处理,这种方式更安全,能应对复杂的转义场景:

import ast

text = r'Your team should include the following \nboard-certified experts:\n \nA pulmonologist is a doctor who\'s an \nexpert of lung diseases.\n'
# 先移除原始字符串的r前缀,再用literal_eval解析
formatted_text = ast.literal_eval(text.removeprefix("r"))

这两种方法都能满足需求,将转义序列生效后的字符串存储到变量中,而非仅通过print输出时才显示格式化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:33:23