# General Translation Python SDKs: 翻译字符串
URL: https://generaltranslation.com/zh/docs/python/guides/translating-strings.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何在 Python 中使用 General Translation 的 t 和 msg 函数，通过变量、上下文和选项来翻译字符串。

[`t`](/docs/python/reference/functions/t) 函数会将 字符串 翻译为当前请求的区域设置。直接编写源语言文本，并使用 ICU 消息语法插入变量值。

## 使用 `t` 翻译 [#t]

将源字符串传给 [`t`](/docs/python/reference/functions/t)。将插值变量作为与 ICU 占位符对应的关键字参数传入，而不是传入 dict。

```python
from gt_flask import t  # 或：from gt_fastapi import t，或：from gt_i18n import t

t("Hello, world!")
t("Hello, {name}!", name="Alice")
```

[`t`](/docs/python/reference/functions/t) 会对源消息进行哈希处理，为当前区域设置查找缓存的翻译，使用 ICU MessageFormat 插入变量；如果没有可用翻译，则回退到插值后的源字符串。当当前区域设置无需翻译时 (例如与默认区域设置一致) ，[`t`](/docs/python/reference/functions/t) 会跳过查找，只进行插值。

## 添加上下文和选项 [#options]

保留选项以下划线作为前缀，因此不会被当作插值变量处理。这三者都会影响消息哈希，所以只要改动其中任何一个，就会生成不同的翻译条目。

* `_context` — 消除具有多重含义的字符串的歧义。
* `_id` — 为条目指定一个稳定的标识符。
* `_max_chars` — 限制翻译的字符长度。

```python
t("Bank", _context="the edge of a river")
t("Welcome", _id="home.hero.title")
t("This is a long message that may need truncation", _max_chars=20)
```

*注意：名称以单个下划线开头的用户变量 (例如 `_name`) 仍会作为插值变量传递；只有上面列出的保留键会被过滤掉。*

## 插入动态值 [#variables]

对于不应被翻译的值 (例如嵌入句子中的用户名) ，请用 [`declare_var`](/docs/python/reference/functions/declare-var) 将其包裹起来，以便在不同语言中保持不变。

```python
from gt_flask import t, declare_var

t(f"Signed in as {declare_var(email, name='email')}")
```

(有关 [`declare_var`](/docs/python/reference/functions/declare-var)、[`derive`](/docs/python/reference/functions/derive) 和相关辅助函数，请参阅[声明变量和变体](/docs/python/guides/declaring-variables))。

## 注册消息以供稍后使用 [#msg]

使用 [`msg`](/docs/python/reference/functions/msg) 可以先为一个 字符串 附加翻译选项，之后再解析它。例如，你可能会在一个地方构建消息，在另一个地方渲染它。不带选项时，[`msg`](/docs/python/reference/functions/msg) 会原样返回该消息；带选项时，它会返回一个编码后的 `{interpolated}:{base64options}` 字符串，之后 [`m_fallback`](/docs/python/reference/functions/m-fallback) 可以对其解码。

```python
from gt_i18n import msg, m_fallback

encoded = msg("Save", _context="button")
# ... 稍后，在渲染时：
m_fallback(encoded)
```

## Next steps

- /docs/python/guides/declaring-variables
- /docs/python/guides/detecting-locale
- /docs/python/guides/storing-translations
- /docs/python/guides/configuring

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
