Text Translation with Claude API — Python

How to translate text between 100+ languages using the Claude API in Python. Covers single-string translation, batch translation, language detection, and quality-controlled output with Pydantic.

💥 50p impulse-buy: Power Prompts PDF (first 10 buyers) 30 battle-tested Claude Code prompts · 8-page PDF · paste into CLAUDE.md and never re-type a prompt again · 50p impulse-buy, no commitment

Claude translates between 100+ languages with strong contextual understanding — it handles idioms, technical terminology, and register (formal/informal) better than pure machine translation systems. This guide covers every common translation pattern in Python.

Installation

pip install anthropic

Minimal translation

import anthropic

client = anthropic.Anthropic()

def translate(text: str, target_language: str) -> str:
    message = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=2048,
        system=f"You are a professional translator. Translate the user's text into {target_language}. Return only the translated text, no explanation.",
        messages=[{"role": "user", "content": text}]
    )
    return message.content[0].text

result = translate("Hello, how are you today?", "Spanish")
print(result)  # "Hola, ¿cómo estás hoy?"

Structured output: translation + detected language

import json

def translate_with_metadata(text: str, target_language: str) -> dict:
    message = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=2048,
        system=(
            "You are a professional translator. Return a JSON object with keys: "
            "'source_language' (detected), 'translation' (translated text), "
            "'confidence' ('high'/'medium'/'low'). No markdown fences."
        ),
        messages=[{"role": "user", "content": f"Translate to {target_language}:

{text}"}]
    )
    return json.loads(message.content[0].text)

result = translate_with_metadata("Bonjour le monde", "English")
# {"source_language": "French", "translation": "Hello, world", "confidence": "high"}

Preserve HTML/Markdown formatting

def translate_markup(html: str, target_language: str) -> str:
    message = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=4096,
        system=(
            f"Translate human-readable text to {target_language}. "
            "Preserve all HTML tags, attributes, href values, and Markdown syntax exactly. "
            "Return only the translated markup."
        ),
        messages=[{"role": "user", "content": html}]
    )
    return message.content[0].text

html_input = "

Welcome to our platform. Learn more.

" print(translate_markup(html_input, "German"))

Batch translation (50% cheaper with Batch API)

strings = [
    "Save changes",
    "Cancel",
    "Are you sure you want to delete this item?",
    "Profile updated successfully.",
]
target = "Japanese"

requests = [
    {
        "custom_id": f"str-{i}",
        "params": {
            "model": "claude-haiku-4-5-20251001",
            "max_tokens": 512,
            "system": f"Translate to {target}. Return only the translation.",
            "messages": [{"role": "user", "content": s}]
        }
    }
    for i, s in enumerate(strings)
]

batch = client.messages.batches.create(requests=requests)
print(f"Batch submitted: {batch.id}")  # poll within 24h for results at 50% cost

Domain-specific translation with glossary

MEDICAL_GLOSSARY = {
    "myocardial infarction": "心肌梗塞",
    "hypertension": "高血压",
    "electrocardiogram": "心电图",
}

glossary_text = "
".join(f"{k} → {v}" for k, v in MEDICAL_GLOSSARY.items())

def translate_medical(text: str) -> str:
    message = client.messages.create(
        model="claude-sonnet-4-6",  # use Sonnet for critical medical content
        max_tokens=4096,
        system=(
            f"Translate medical text to Simplified Chinese.
"
            f"Apply this glossary exactly:
{glossary_text}
"
            "Preserve all medical term precision."
        ),
        messages=[{"role": "user", "content": text}]
    )
    return message.content[0].text

Claude vs dedicated MT APIs

CriterionClaude APIGoogle TranslateDeepL
Languages supported100+13333
Context/idiom handlingExcellentGoodVery good
Terminology/glossaryPrompt-based, flexibleCustom model (paid)Glossary API
Formatting preservationInstruction-basedHTML mode built-inTag handling built-in
Speed (short strings)~1–2s~100ms~200ms
Cost per 1M chars~$1–6 (Haiku–Sonnet)$20$25
Best forLong-form, nuanced, domain-specificReal-time, high-volumeEuropean language pairs

For bulk translation jobs, estimate costs with the Claude API Cost Calculator. For text summarization across languages, see the summarization guide.

Frequently asked questions

Can Claude translate between any two languages?
Claude supports translation between 100+ languages including low-resource languages often missed by commercial MT APIs. Quality is highest for high-resource language pairs (English ↔ Spanish/French/German/Chinese/Japanese/Korean). For obscure language pairs, add 'Check your translation for accuracy' to the system prompt to trigger self-verification.
How is Claude translation different from Google Translate or DeepL?
Claude handles context, register, and domain-specific terminology far better than pure MT systems. It can localize idioms, preserve formatting markup, apply a specific style guide, and translate technical jargon correctly without a glossary. The trade-off: Claude is slower and more expensive per character than dedicated MT APIs.
How do I detect the source language before translating?
Include 'Detect the source language, then translate to {target}' in your prompt. Claude returns the detected language alongside the translation. Alternatively, call Claude once for detection (structured JSON output: `{language, confidence}`) and once for translation to keep concerns separate.
What is the cheapest model for bulk translation?
Use `claude-haiku-4-5-20251001` for straightforward translation tasks — it's 10× cheaper than Sonnet and fast. Use the Batch API for offline bulk jobs at 50% further discount. Reserve Sonnet for high-stakes content (legal, marketing copy) where register and nuance matter.
How do I preserve HTML or Markdown formatting during translation?
Explicitly instruct Claude: 'Translate only the human-readable text. Preserve all HTML tags, attributes, and Markdown syntax exactly as they appear.' Claude reliably respects this constraint for well-formed markup.

Free tools

Cost Calculator → API Cookbook → Diff Summarizer → Skills Browser →

More examples

Claude API Python QuickstartClaude API Node.js / TypeScript QuickstartClaude API Streaming in PythonClaude API Streaming in Node.js / TypeScriptClaude API Tool Use in PythonClaude API Tool Use in Node.js / TypeScript