# python: 文字列翻訳のパターン
URL: https://generaltranslation.com/ja/docs/python/guides/strings.mdx
---
title: 文字列翻訳のパターン
description: Python で `t()`、`msg()`、変数、`derive()` を使って文字列を翻訳する方法
---
GT の Python ライブラリで文字列を翻訳する方法は 2 つあります。
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()` はどちらも同じ訳文を生成します。同じ文字列が複数箇所で使われる場合や、すべての文字列を 1 つのファイルにまとめたい場合は、`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) — ロケールのコンテキストがどのように機能するか