# python: 字符串翻译模式
URL: https://generaltranslation.com/zh/docs/python/guides/strings.mdx
---
title: 字符串翻译模式
description: 在 Python 中使用 t()、msg()、变量和 derive() 进行字符串翻译
---
在 GT 的 Python 库中,翻译字符串有两种方式:
1. **使用 `t()` 进行内联翻译** — 直接在路由处理函数中翻译字符串
2. **使用 `msg()` 预先注册** — 在模块级作用域中定义字符串,并在 runtime 时解析
## 使用 `t()` 进行内联翻译
使用 [`t()`](/docs/python/api/t) 按当前请求的区域设置翻译字符串:
```python
from gt_flask import t
@app.route('/api/greeting')
def greeting():
return { 'message': t('Hello, world!') }
```
```python
from gt_fastapi import t
@app.get('/api/greeting')
def greeting():
return { 'message': t('Hello, world!') }
```
## 使用 `msg()` 预先注册字符串
使用 [`msg()`](/docs/python/api/t) 在模块级作用域中注册字符串,然后在处理函数中调用它们:
```python title="messages.py"
from gt_flask import msg # 或 gt_fastapi
GREETING = msg('Hello, world!')
WELCOME = msg('Welcome, {name}!')
NOT_FOUND = msg('Resource not found.')
```
```python title="routes.py"
from messages import GREETING, WELCOME, NOT_FOUND
@app.route('/api/greeting')
def greeting():
return {
'greeting': GREETING(),
'welcome': WELCOME(name='Alice'),
}
@app.errorhandler(404)
def not_found(e):
return { 'error': NOT_FOUND() }, 404
```
`t()` 和 `msg()` 得到的译文完全相同。当同一个字符串会在多个位置使用,或你希望把所有字符串集中到同一个文件中时,请使用 `msg()`。
## 变量插值
### 使用 `t()`
使用 `{name}` 占位符,并将值作为关键字参数传入:
```python
t('Welcome, {name}!', name=user.display_name)
t('You have {count} new messages.', count=unread_count)
```
### 使用 `declare_var()` 和 `decode_vars()`
如果你需要更灵活地控制变量处理方式,请使用 [`declare_var()`](/docs/python/api/declare-var) 和 [`decode_vars()`](/docs/python/api/decode-vars):
```python
from gt_flask import declare_var, decode_vars
template = t('Hello, {name}! You have {count} items.')
result = decode_vars(template, {
'name': declare_var('name', 'Guest'),
'count': declare_var('count', 0),
})
```
## 使用 `derive()` 处理词语一致性
[`derive()`](/docs/python/api/derive) 可生成符合语法的一致性变体——这对那些词语会随上下文 (如性、数、格) 变化形式的语言尤其有用:
```python
from gt_flask import t, derive
count = 3
item_word = derive('item', {'one': 'item', 'other': 'items'})
message = t('You have {count} {item}.', count=count, item=item_word)
```
更多 pattern,请参阅 [derive 教程](/docs/python/tutorials/derive)。
## 使用 `$context` 消除歧义
有歧义的字符串可能导致译文不准确。添加 `$context` 为翻译器提供上下文:
```python
t('Apple', context='the technology company')
t('Spring', context='the season, not a coil')
t('Bank', context='a financial institution')
# 同样适用于 msg()
APPLE = msg('Apple', context='the fruit')
```
## 后续步骤
* [`t()` API 参考](/docs/python/api/t)
* [`declare_var()` API 参考](/docs/python/api/declare-var)
* [`derive()` API 参考](/docs/python/api/derive)
* [区域设置检测与中间件](/docs/python/guides/middleware) — 了解区域设置上下文的工作方式