# General Translation Python SDKs: 文字列を翻訳する URL: https://generaltranslation.com/ja/docs/python/guides/translating-strings.mdx --- title: 文字列を翻訳する description: Python で General Translation の `t` 関数と `msg` 関数を使って、変数、コンテキスト、オプション付きで文字列を翻訳する方法。 related: links: - /docs/python/guides/declaring-variables - /docs/python/guides/detecting-locale - /docs/python/guides/storing-translations - /docs/python/guides/configuring --- [`t`](/docs/python/reference/functions/t) 関数は、文字列を現在のリクエストで有効なロケールに翻訳します。原文をそのまま記述し、ICU メッセージ構文で値を埋め込んでください。 ## `t` で翻訳する [#t] `t` はソース文字列を指定して呼び出します。補間値は dict ではなく、ICU のプレースホルダーに対応するキーワード引数として渡してください。 ```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` はソースメッセージをハッシュ化し、現在のロケール向けにキャッシュされた翻訳を参照し、ICU MessageFormat を使って変数を補間し、翻訳が存在しない場合は補間済みのソース文字列にフォールバックします。現在のロケールで翻訳が不要な場合 (たとえば、デフォルトロケールと一致する場合) 、`t` は参照をスキップし、補間のみを行います。 ## コンテキストとオプションを追加する [#options] 予約済みオプションは、補間変数として扱われないよう、先頭にアンダースコアが付いています。これら 3 つはいずれもメッセージハッシュに影響するため、どれか 1 つでも変更すると別の翻訳エントリになります。 * `_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`、[`derive`](/docs/python/reference/functions/derive)、および関連するヘルパーについては、[変数とバリアントの宣言](/docs/python/guides/declaring-variables)を参照してください。 ## 後で使うメッセージを登録する [#msg] [`msg`](/docs/python/reference/functions/msg) を使うと、文字列に翻訳オプションを今の時点で付けておき、あとで解決できます。たとえば、ある場所でメッセージを組み立て、別の場所でレンダリングする場合です。オプションなしの場合、`msg` はメッセージをそのまま返します。オプションを指定すると、[`m_fallback`](/docs/python/reference/functions/m-fallback) があとでデコードできる、エンコード済みの `{interpolated}:{base64options}` 文字列を返します。 ```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