Lesson 3.3 · 3 of 4 · 4 min read · Reviewed 24 Nov 2026
Estimating tokens for text, code and images
By the end, you can
- Estimate tokens for text, code and images.
- Use the token counting API for exact numbers.
Rough rules for text
| Content | Rough guide |
|---|---|
| Plain English prose | About 3 to 4 characters per token |
| Code | Often more tokens than prose of the same length (symbols, indentation) |
| Numbers and ids | Long numbers split into several tokens |
| Many non-English languages | Often more tokens per word |
| JSON and tables | Keys, quotes and brackets add tokens |
These are only estimates. Different models use different tokenizersTokenizer: The component that splits text into tokens and maps each token to an id the model can process..
Exact counts
The Messages APIMessages API: The chat API endpoint that takes a list of messages and returns the next assistant message. has a token countingToken counting: Measuring how many tokens a request will use before sending it, for example with a token-counting endpoint. endpoint. Send the same system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation., tools and messages you plan to send, and it returns the input tokenInput tokens: The tokens you send in a request: system prompt, tool definitions, conversation history and attached content. count for that model, without generating anything.
count = client.messages.count_tokens(
model="<model id>",
system="...",
messages=[{"role": "user", "content": "..."}],
)
print(count.input_tokens)
Images
Images become input tokens based on their size. Claude’s visionVision: A model’s ability to read and reason about images, such as screenshots, charts and photos. docs give an approximate formula (width times height in pixels, divided by about 750) and recommend resizing very large images, since beyond a certain size they’re scaled down anyway.
PDFs
PDF pages are processed as text plus page images, so each page costs more than its text alone (8.1).
Key points
- Tokens are pieces of words; in English, one token is often around three to four characters, but it varies.
- Code, numbers, non-English text and unusual formatting often use more tokens per character.
- For exact counts, use the token counting endpoint; for images, cost grows with image size.
Check estimates against counted tokens
Compare the 4-characters rule with an exact count for prose, code and JSON.
You will have: A table of estimate, counted tokens and their ratio for three content types.
Steps
- Estimate each sample at 4 characters per token.
- Call count_tokens with the same text to get the exact input count.
- Print the estimate, the count and their ratio.
- Note which content types the rule of thumb gets most wrong.
Done when
- Every sample shows both an estimate and a counted number.
- The ratio is printed for each sample.
- You can name the sample where the estimate is furthest off.
Open in the Playground No API key needed.
Starter code (Python)
import json
import anthropic
client = anthropic.Anthropic()
samples = {
"prose": "Our returns policy lets you send back unworn shoes within 30 days for a full refund. " * 4,
"code": "def total(items):\n return sum(i['price'] * i['qty'] for i in items if i.get('qty'))\n" * 4,
"json": json.dumps([{"order_id": 100231 + i, "sku": f"SKU-{i:04d}", "qty": i % 3 + 1} for i in range(6)]),
}
for name, text in samples.items():
estimate = len(text) // 4
# TODO: get the exact count with client.messages.count_tokens(model=..., messages=[...]).input_tokens
# TODO: print estimate, counted and their ratio
print(f"{name:5} chars={len(text):4} estimate={estimate:4}")
Show a solution
import json
import anthropic
client = anthropic.Anthropic()
samples = {
"prose": "Our returns policy lets you send back unworn shoes within 30 days for a full refund. " * 4,
"code": "def total(items):\n return sum(i['price'] * i['qty'] for i in items if i.get('qty'))\n" * 4,
"json": json.dumps([{"order_id": 100231 + i, "sku": f"SKU-{i:04d}", "qty": i % 3 + 1} for i in range(6)]),
}
for name, text in samples.items():
estimate = len(text) // 4
counted = client.messages.count_tokens(
model="claude-sonnet-5-5", messages=[{"role": "user", "content": text}]
).input_tokens
print(f"{name:5} chars={len(text):4} estimate={estimate:4} counted={counted:4} ratio={counted / max(1, estimate):.2f}")
print("Trust the counted number when it matters; the estimate is only a rule of thumb.")