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

Python中如何让print()保留字符串\n并识别三引号真实换行?

保留游戏文本翻译中的\n字符并正常显示真实换行

问题背景

现有一个调用GPT-4进行游戏英文文本西语本地化的Python函数,要求保留原文本的标点、大小写、真实换行以及字符串中的\n字符,但当前执行后,输出中的\n被转换为实际换行符,无法保留原样。

原函数代码

import openai

def translate(text):
    while True:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are a translator, you will receive English language sentences from a videogame needing localization. You must respect the punctuation and capitalization. You must maintain \n as is"},
                {"role": "system", "content": "The target language is Spanish"},
                {"role": "user", "content": text}
            ],
            temperature=0
        )
        return response.choices[0].message['content']

输入文本

text_to_translate = """
Blocks melee and\n ranged units' line of sight.
Sink the unit. Sunken\n units are more vulnerable to enemy attacks.
Teleport the unit through\n this portal to an exit portal.
"""

当前问题输出

执行翻译并print()后,\n被转为实际换行:

Bloquea la línea de visión de
unidades de combate cuerpo a cuerpo y a distancia.
Hunde la unidad. Las unidades
hundidas son más vulnerables a los ataques enemigos.
Teletransporta la unidad a través
de este portal a un portal de salida.

解决方案

要实现真实换行正常生效且**\n字符保留原样**,需从输入定义、提示词优化两方面调整:

1. 修正输入文本的定义

使用Python的原始字符串(前缀r)定义输入,这样字符串中的\n会被当作普通字符(而非转义换行符)保留,同时三引号内的真实换行仍正常生效:

text_to_translate = r"""
Blocks melee and\n ranged units' line of sight.
Sink the unit. Sunken\n units are more vulnerable to enemy attacks.
Teleport the unit through\n this portal to an exit portal.
"""

2. 优化GPT提示词

明确告知GPT需严格区分真实换行和\n字符,避免将\n转换为实际换行:

def translate(text):
    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "你是游戏本地化翻译员,将给定英文文本翻译为西班牙语。严格保留所有标点、大小写、原始换行,并且**完全保留字符串中的`\\n`字符,不要将其转换为换行**。"},
            {"role": "user", "content": text}
        ],
        temperature=0
    )
    return response.choices[0].message['content']

注:提示词中使用\\n是为了让GPT正确识别\n作为字符,而非换行指令。

3. 验证输出

调整后执行翻译并print(),将得到符合要求的结果:

Bloquea la línea de visión de unidades cuerpo a cuerpo y\n unidades a distancia.
Hunde la unidad. Las unidades\n hundidas son más vulnerables a los ataques enemigos.
Teletransporta la unidad a través\n de este portal a un portal de salida.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:42:53