DeepSeek can help you investigate Unicode bugs, but the application must decide what “the same text” means. A search field, an account identifier, a display name and an archived document can require four different answers. The safest starting point is to preserve the received text, define each derived representation explicitly, and test the boundaries before changing production data.
This guide develops that workflow around a small fictional catalog. You will compare visually similar strings, build a collision-preserving search index, inspect misleading length measurements, and turn a vague AI suggestion into a reviewable text policy. The downloadable Python lab runs locally without a model account, API key, network request or third-party Python package. The examples are original synthetic fixtures rather than samples from customer records.
Evidence boundary: the Python examples and their stated outputs were tested locally. The prompts are proposed review instructions; they are not transcripts of a DeepSeek session. This article reports no measured DeepSeek accuracy, provider-side Unicode guarantee or benchmark advantage. Standards and documentation were checked on October 5, 2026. Keep the runtime and Unicode database versions in your own test report because documentation and deployed interpreters can differ.
1. Define the text contract before asking for code
Imagine a catalog whose records contain a permanent record ID and an editor-supplied label. An editor enters “Café” on one device and a second editor supplies “Cafe” followed by a combining acute accent on another. Both labels may look identical. A literal comparison nevertheless sees different sequences. A developer asks an assistant to “fix duplicate Unicode names,” and receives a one-line normalization function. The function might be correct for one comparison while the implied deletion policy is completely wrong.
The first task is therefore a small decision document. State whether the field is a label, an identifier or evidence that must be reproduced exactly. Identify who is allowed to merge records. Say whether case differences should affect search, whether accents should matter, and whether a search can return several candidates. Add the unit used for input limits. A requirement such as “maximum 80 characters” is incomplete until the team names what it counts and where that limit is enforced.
For our catalog, the contract is intentionally modest. The record ID remains the identity. We retain the original Python string, derive an NFC display value, and derive a separate case-insensitive search key. A search key maps to a collection of records. Matching keys never authorize a merge, an account lookup or a destructive overwrite. Display and search transformations can evolve without silently replacing the archived input.
That decision is a useful review target for DeepSeek. Ask it to locate ambiguities and propose counterexamples before requesting an implementation. A response that immediately recommends lowercasing every database column has skipped the central question. The useful output is a list of observable behaviors and disputed cases that a person can approve. The broader method in our guide to traceable acceptance criteria helps turn those decisions into tests.
2. Keep original, display and search values separate
One field can serve several consumers without forcing them to share the same representation. In the example record, raw text answers “what string did the importer receive?” The display value answers “what canonical form does this interface use?” The search key answers “which records should this particular comparison consider candidates?” Each value has a purpose, and none replaces the permanent ID.
Raw string preservation is narrower than preserving the original file. Once a decoder has turned bytes into text, the application may already have discarded a byte-order mark, normalized line endings or applied an error policy. If the product needs exact uploaded-file reproduction, archive the original bytes with appropriate access controls and retention. Our lab preserves the string it receives; it does not claim to reconstruct an earlier byte stream or an external system’s document formatting.
Keeping all three values can look redundant in a tiny demo. Its value becomes visible during a policy change. Suppose support reports that a newly broadened search returns two unrelated catalog items. With the original labels and stable IDs intact, you can inspect the collision and rebuild the search index. If the old importer replaced both labels with a derived key and discarded one record, the same investigation becomes a data-recovery problem.
Use names that make the distinction difficult to miss. A field called normalized_name invites callers to assume it is appropriate everywhere. Names such as raw_label, display_label_nfc and search_key_v1 carry more context. Documentation should say that the key is nonunique and unsuitable for authentication. In a database schema, the collection of matches must remain representable; a unique constraint on the derived key would contradict this example’s contract.

3. Understand what NFC and NFKC change
Unicode Standard Annex #15 distinguishes canonical equivalence from compatibility equivalence. NFC and NFD handle canonical relationships; NFKC and NFKD also apply compatibility mappings. NFC performs canonical decomposition followed by composition, while NFD leaves the decomposed form. The “K” forms can remove distinctions that matter in some contexts. That is why normalization should be a field-level policy rather than an indiscriminate cleanup operation.
Consider three local fixtures. Composed é and e plus a combining acute accent converge under NFC. A fullwidth capital A remains distinct from ASCII A under NFC but becomes A under NFKC. The single ligature ff remains unchanged by NFC while NFKC expands it to ff. These examples make the trade-off concrete: a compatibility mapping may improve one search experience and destroy a distinction needed by another application.
For a document archive, a scientific label or a quoted source, an instruction to “make everything ordinary ASCII” deserves particular scrutiny. Our recommended review procedure is to display the original, proposed replacement and code-point sequence side by side. Ask the owner of the field whether the distinction is meaningful. A change should be explained as an explicit transformation with known information loss, not as a neutral repair of allegedly bad characters.
Do not assume that concatenating already normalized fragments preserves normalization. Annex #15 explicitly discusses this boundary. In our fixture, the string containing only e is already NFC, and a string containing only the combining acute accent is also NFC. Joining them creates a sequence that NFC can compose into é. For a final comparison value, normalize after the relevant assembly step rather than relying on a claim about each fragment in isolation.
The practical question to put to DeepSeek is therefore specific: “Which fixture changes under this proposed policy, and why is that change acceptable for this field?” Request an explanation of the fullwidth and ligature examples separately. If the answer treats every visual difference as irrelevant, return to the contract. A successful demonstration on accented Latin text is useful evidence, but it does not establish suitability for every script or every downstream use.
4. Casefolding is a search choice, not a universal equality rule
Python documents casefold as a more aggressive operation than lowercasing for caseless matching. Its familiar example is the German sharp s: ß becomes ss. Our catalog consequently treats Straße and STRASSE as sharing a search key. It still preserves their original labels and separate record IDs. A search for that key returns both candidates so the interface can display enough context for a deliberate selection.
The lab uses a deliberately named application policy: apply NFC, then casefold, then NFC again. This is a reproducible recipe for the example catalog, not a claim to implement every Unicode equivalence algorithm or every language’s preferred search behavior. The first and final normalization steps each have regression fixtures in the lab. Removing a step because it appears redundant on ASCII input changes the implementation being reviewed.
There is an important trap in describing this recipe. Using NFC does not mean that the whole pipeline preserves every compatibility distinction. Casefold itself expands the ff ligature to ff. Conversely, the fullwidth A fixture and ASCII A still produce different keys under this recipe. The result is more selective than simply applying NFKC to everything, and it must be explained with actual outputs rather than a broad label such as “safe normalization.”
Nor does this recipe remove accents, trim whitespace or resolve spelling variants. Café and cafe remain different search keys. A label with a trailing space retains that space. If the product wants accent-insensitive search, whitespace handling or locale-specific behavior, define another policy and add examples for each new equivalence. Combining multiple transformations under one helper name makes it harder to discover which decision produced an unwanted match.
Language-sensitive comparisons require particular care. Test Turkish I, İ and ı as distinct fixtures rather than assuming a universal English-style lowercase rule matches the product’s needs. Ask a language specialist or the product owner what the search should do. The example code is a deterministic candidate-generation tool. It does not decide which labels are linguistically interchangeable, which order users expect, or which record a person intended to select.
5. Preserve collisions instead of hiding them
The most consequential line in a normalization patch may be the dictionary assignment after the transformation. A loop that writes index[key] = record can quietly replace an earlier record when two labels share a key. That mistake can survive tests that only check whether the final key looks correct. A reviewer must inspect how the key is consumed, including storage constraints, lookups, cache entries and any automatic merge operation.
Our index maps each key to a list. In the diagram, the Straße record has ID R-101 and the STRASSE record has ID R-102; the downloadable fixtures use descriptive IDs for the same comparison. Both appear under strasse. The input order is retained in this small example, but production ranking should be defined independently. The user interface should show the stable ID or other legitimate distinguishing context when labels are ambiguous. Returning one arbitrary candidate is not an acceptable substitute for an explicit selection rule.
This also changes the acceptance test. Instead of asserting that a search “finds the item,” assert the complete candidate collection and the number of preserved records. Reverse the input order and verify that no record disappears. Add a third unrelated item and prove it remains in a different bucket. Finally, test the duplicate-ID rule separately from text collisions. Two records sharing a label key and two inputs claiming the same permanent ID are different problems.
A useful production metric is the distribution of bucket sizes after a policy change. A sudden rise in large buckets can reveal an overly broad transformation or a bad import. Report aggregate counts and carefully selected synthetic examples during review rather than sending customer labels to an external model by default. Our data-minimization workflow explains how to reduce what leaves the application while preserving useful diagnostic evidence.

6. Run the original Python lab
The accompanying lab includes a small record model, the named search-key function, a collision-preserving index, explicit expected outputs and a separate invariant sweep. Everything is local. Use a clean working directory, read the README, and run the commands shown below from the extracted code folder. There is no installation command because the implementation uses the Python standard library.
Download the Unicode handling lab ZIP. The archive includes source, tests and the recorded local results. Treat the included receipts as evidence about the tested environment. Rerun the tests on the interpreter that will actually execute your application. In particular, compare the reported Python version and Unicode database version before treating a difference as a bug in the transformation.
python3 -m unittest -v test_unicode_lab.py
python3 demo.py
python3 validate_all_codepoints.py
The central function is intentionally small enough to inspect. Its input is a Python string, and invalid input types are rejected instead of being silently converted with str. A bytes value needs an explicit decoding decision before entering this function. The function does not remove formatting controls, determine grapheme clusters, validate an identifier or escape text for HTML. Those are separate boundaries with separate requirements.
"""Small Unicode search policy; no I/O, network, deduplication, or ID guarantees.
Input is already-decoded Python text. Raw means the original str, not source bytes.
"""
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
import unicodedata
def _require_text(text: str, name: str = "text") -> None:
if not isinstance(text, str):
raise TypeError(f"{name} must be str")
def display_value(text: str) -> str:
"""Return NFC text, allowing empty strings and preserving case/whitespace."""
_require_text(text)
return unicodedata.normalize("NFC", text)
def search_key(text: str) -> str:
"""Return the nonunique policy key NFC(casefold(NFC(text))).
This is locale-independent Python casefolding. It is not an identity key,
security check, compatibility-normalization policy, or accent remover.
"""
_require_text(text)
return unicodedata.normalize("NFC", display_value(text).casefold())
def code_points(text: str) -> tuple[str, ...]:
"""Describe code points, not grapheme clusters, glyphs, or byte positions."""
_require_text(text)
return tuple(f"U+{ord(character):04X}" for character in text)
@dataclass(frozen=True)
class TextRecord:
"""An unchanged raw str plus an application-supplied, nonempty label.
record_id is not normalized or checked for uniqueness. Derived properties
cannot disagree with raw; persist raw alongside the derived display value
and version your search policy if materializing keys in a database.
"""
record_id: str
raw: str
def __post_init__(self) -> None:
_require_text(self.record_id, "record_id")
_require_text(self.raw, "raw")
if not self.record_id:
raise ValueError("record_id must not be empty")
@property
def display(self) -> str:
return display_value(self.raw)
@property
def key(self) -> str:
return search_key(self.raw)
def build_search_index(records: Iterable[TextRecord]) -> dict[str, list[TextRecord]]:
"""Keep every input occurrence in a list, in input order, for each key."""
index: dict[str, list[TextRecord]] = {}
for record in records:
if not isinstance(record, TextRecord):
raise TypeError("every record must be TextRecord")
index.setdefault(record.key, []).append(record)
return index
def find_matches(
index: Mapping[str, Sequence[TextRecord]], query: str
) -> tuple[TextRecord, ...]:
"""Return a tuple snapshot for exact policy-key lookup; no fuzzy search."""
return tuple(index.get(search_key(query), ()))
Read the expectations before reading the implementation. For the café pair, the relevant expectation is that two raw representations remain observable while the chosen search policy groups them. For the sharp-s pair, the expectation is a shared key with two preserved records. For the fullwidth example, the expected inequality guards against accidentally replacing the declared policy with a more aggressive compatibility mapping.
The tests also include less obvious cases where normalizing before or after casefold makes a measurable difference. These fixtures are valuable during refactoring: an engineer who sees three short operations may be tempted to collapse them without checking the contract. A regression suite should explain the purpose of each step through a failure that is understandable, not merely by asserting that the current implementation equals a copy of itself.
Our local test report is available in the archive. It separates named examples from a broad single-code-point sweep. The latter checks declared invariants across the Python code-point range; it does not test every possible multi-code-point string. That distinction matters because composition, combining-mark order and emoji sequences involve interactions between code points. A large input count is useful coverage evidence, but it is never a proof that every text workflow is correct.
7. Name the unit whenever you say “length”
Python’s len reports the number of items in a string, which means code points for a Python str. UTF-8 byte length is a different measurement obtained after encoding. A user-perceived character can involve several code points. Unicode Standard Annex #29 defines extended grapheme-cluster boundaries, which provide a useful default segmentation model; product behavior can still require tailoring and careful testing.
For the decomposed café fixture, Python sees five code points, and UTF-8 encoding uses six bytes. The NFC form has four code points and five UTF-8 bytes. Both can appear as the same four visible letters. If a database column allows five bytes while the form allows five code points, one representation fits and the other may not. A test should record the values at both boundaries rather than treating a front-end character counter as evidence about storage.
The family emoji fixture in the lab contains four person emoji joined by three zero-width joiners: seven code points and twenty-five UTF-8 bytes. A supporting renderer may display it as one family glyph. Rendering varies with fonts and platforms, so use the exact escaped sequence when sharing a bug report. A screenshot alone does not tell a reviewer which sequence was stored or whether a joiner was lost.
A truncation feature needs its own specification. Slicing a Python string by code-point index can separate an accent from its base or cut an emoji sequence. Cutting encoded bytes can split a multibyte UTF-8 sequence. For a user-facing “shorten to N visible characters” feature, use a maintained grapheme-segmentation implementation appropriate to the platform and test representative scripts. The standard-library lab intentionally does not invent a segmentation algorithm from combining-class checks.
Ask DeepSeek to label every proposed limit with its unit and enforcement point. Distinguish transport bytes, decoded code points, extended grapheme clusters and UI layout width. A field can legitimately need more than one limit. The review question is whether the implementation communicates those limits, rejects inputs predictably and avoids changing already accepted text merely to force it through a poorly specified boundary.
8. Keep decoding errors visible
Normalization operates on text that has already been decoded. It cannot reliably recover the original bytes after a mistaken decoder or a lossy error handler has changed them. Python’s codec documentation distinguishes strict failures from replacement and ignore strategies. The appropriate choice depends on the input contract; silently ignoring undecodable bytes is especially dangerous when the application needs to explain exactly what was imported.
For our fictional catalog importer, the recommended contract is UTF-8 with a visible error on invalid input, followed by a separate review queue for failed rows. That is an example policy, not a universal rule for every file format. If a supplier legitimately sends another encoding, record that encoding in the import configuration. Do not ask a model to guess the encoding from a damaged label and then overwrite the only copy of the file.
A repair workflow should retain the original bytes, the selected decoder, the error details and a proposed replacement as separate evidence. Have a person confirm the interpretation when it matters. In a support ticket, a short hex excerpt and an escaped decoded string can be more useful than a long screenshot. Redact sensitive content without removing the bytes or code points needed to reproduce the specific failure.
Also separate import success from display success. Text may decode and compare correctly while the chosen font lacks a glyph. Conversely, a screen can show two labels that appear identical while their stored code points differ. Replacing every unfamiliar symbol with a question mark may make a screen look simpler, but it destroys the evidence needed to diagnose either problem. A careful investigation identifies the failing boundary first.
9. Normalization does not establish identity or safety
Unicode Technical Standard #39 describes mechanisms for investigating confusable characters and identifier restrictions. Those mechanisms solve different problems from canonical normalization. A Latin a and a Cyrillic а can look similar in some fonts while remaining different characters. NFC does not convert them into one trusted identity, and a shared search key would not prove that two account names belong to the same person.
Keep the consequences proportional to the field. A catalog search can return several candidates and let a reader inspect them. Account recovery, access-control decisions and payment destinations cannot rely on this tutorial’s label-search policy. Those flows need their own reviewed identifier rules and stable authoritative identifiers. Do not expand a helpful text-comparison patch into an authentication-policy change just because the same helper function is easy to reuse.
Invisible and directional formatting characters should likewise be investigated in context. Some are necessary for legitimate text behavior. A blanket rule to delete everything classified as a mark or a format character can damage writing systems and emoji sequences. For an administrative review screen, showing escaped code points alongside the original rendering is often more informative than silently removing unfamiliar characters and then declaring the result clean.
Output encoding remains a separate responsibility. A normalized string is not automatically safe to insert into HTML, SQL or a shell command. Use the correct escaping or parameterization for the actual output context, and retain those tests when reviewing a Unicode change. If DeepSeek proposes normalization as a replacement for an existing security boundary, reject that substitution and ask it to identify the original threat that the boundary addressed.
10. Give DeepSeek a bounded review packet
A focused review packet contains the field contract, a small relevant code excerpt, the exact runtime versions and a set of escaped synthetic fixtures. Include both expected matches and expected nonmatches. State what the patch is allowed to change and what it must preserve. This prevents the discussion from drifting into a general rewrite of the importer, database schema or authentication system.
The official DeepSeek chat-completions documentation describes a conversation-based request with a model and messages. The review workflow here can be used conversationally without depending on a particular model alias or an unverified feature claim. If you automate it, verify the current provider documentation separately and record the configuration. The model response remains a proposal that must survive the same local tests as a human-authored patch.
Review this Unicode search policy against the contract below.
Do not change identity, authentication or source records.
Contract:
- Preserve the received Python str as raw.
- Derive display text with NFC.
- Derive a nonunique key: NFC(casefold(NFC(text))).
- Retain every input occurrence in each key bucket.
- Never use the key as a unique identifier or security check.
- Keep accents and whitespace; do not add transliteration.
Fixtures include composed/decomposed café, Straße/STRASSE,
fullwidth A/ASCII A, ff/ff and the family emoji sequence.
Return findings with a minimal escaped input, the expected
behavior, the consequence and the smallest relevant fix.
Separate contract violations from alternative product policies.
Flag any assumption requiring a human decision.
Do not claim you ran the code unless you actually did.
Ask for findings with a reproducible input, an expected result, the observed risk and the smallest relevant fix. A response such as “Unicode is complicated; use a library” is incomplete for a three-line comparison function. Conversely, a confident replacement with no counterexample is not enough evidence to change a text policy. Require the reviewer to distinguish a defect relative to the declared contract from a possible alternative product behavior.
Run a second pass that attacks the test design. Ask which assumptions appear in both the implementation and the expected-output generator. Request a fixture that would fail if a normalization step were removed, a collision were overwritten or a byte count were mistaken for a code-point count. Keep expected values literal when practical. Our evidence-driven code review guide offers a reusable format for these findings.
Do not paste a production database export simply to provide realism. The difficult Unicode behavior can usually be represented by a tiny synthetic string plus its escape sequence. If the bug depends on a specific sensitive value, minimize the excerpt and follow the organization’s data-sharing rules. A model does not need a person’s real name, account history or private document to explain why two code-point sequences compare differently.
11. Test the contract from more than one direction
Start with example tests that explain business intent. Preserve the raw label exactly. Assert the expected display value and the complete candidate bucket. Test the distinctions the policy intentionally keeps, including fullwidth versus ASCII text, accents and trailing whitespace. A negative expectation is as important as a positive match: it detects a future “helpful” transformation that broadens the search without approval.
Next, add properties that should hold under the named policy. Applying the display normalization twice should give the same display value. Applying the search-key function to its own output should be stable for the tested inputs. Every input occurrence should be retained exactly once in the index; repeated occurrences must not disappear. An empty search, an invalid type and a repeated record ID should each follow an explicitly documented path. This lab permits empty text and repeated IDs; ID uniqueness belongs to the application that supplies the records.
Then perturb the implementation deliberately. Remove the final normalization and check that the corresponding regression fails. Replace the list-valued index with a single assignment and verify that the collision test catches the lost record. Change NFC to NFKC and check that the fullwidth nonmatch fails. These small fault injections tell you whether the test suite protects the decisions you care about, rather than merely executing the code.
Separate breadth from independence. Iterating over many code points can reveal edge behavior, but a test that calculates its expected answer with the same function has little power to detect a mistaken policy. Combine literal fixtures, record-conservation checks, deliberate faults and bounded generated cases. The property-based testing guide explains how to use broader input exploration without confusing a passed run with exhaustive proof.
Finally, keep a small display review in the release process. Copy-and-paste fidelity, cursor movement, selection, text wrapping and assistive-technology output are not established by a backend equality test. Check the actual product on its supported environments using meaningful examples. The Python lab establishes facts about its strings and index; it does not certify the accessibility or internationalization behavior of a browser, operating system or database collation.
12. Release a new text policy without erasing the old evidence
Treat a search-policy revision as a data change even when the patch is short. Give the policy a version, calculate proposed keys into a separate field or index, and compare collision counts before switching readers. Keep the original labels and stable IDs intact. A rollback should restore the previous search behavior without requiring anyone to guess how transformed values used to look.
For our catalog, an initial shadow run would compute search_key_v2 alongside v1 while continuing to serve v1 results. Review buckets that split or merge, and sample expected nonmatches that changed. The relevant release evidence is the difference in behavior, not just a green test runner. Do not automatically merge records to make a new unique constraint succeed; that would introduce an additional decision outside the comparison policy.
Coordinate writers and readers during the switch. If imports create one version of the key while queries generate another, the system can appear to lose records even though both functions work individually. Record the runtime, Unicode data version, policy version and deployment boundary together. Rebuild derived indexes using an explicit migration plan, and test how retries or interrupted batches avoid partial, inconsistent search results.
Use a short release checklist: approved field contract, preserved original values, literal Unicode fixtures, collision conservation, explicit length units, visible decoding failures, contextual output escaping, a rollback route and honest test scope. These checks make the result reviewable by someone who did not participate in the model conversation. They also give DeepSeek a concrete acceptance target for a later patch instead of a vague request to “handle Unicode better.”
Common questions
Should every string be converted to NFC?
No single rule fits every boundary. NFC is the chosen display form in this tutorial, while the original string remains available. Protocols, identifiers, archived evidence and external systems may impose different requirements. Decide at the field boundary, document the policy, and test its consumers rather than silently applying it to every value moving through the program.
Can I use the search key as a unique database key?
That would contradict this lab’s design. The key deliberately groups multiple records, including Straße and STRASSE. Use stable record IDs for identity and represent the full candidate collection in the search index. If a product needs a unique identifier, specify and review that identifier’s rules separately, including how existing collisions are resolved by an authorized owner.
Does this guide implement grapheme-aware truncation?
No. It demonstrates why code-point and byte counts are insufficient for that requirement, then leaves segmentation to a suitable maintained implementation. The family-emoji example is an explanatory fixture, not a homegrown grapheme parser. Verify the platform’s segmentation behavior and supported Unicode version before using it to enforce a user-facing length contract.
What should I do when DeepSeek proposes a different recipe?
Ask which approved requirement the change satisfies, request a minimal input that demonstrates the difference, and run the candidate against your positive and negative fixtures. Keep the old policy available during the comparison. Adopt the change only when its observed behavior matches the intended product decision and its operational consequences are understood.
Sources & References
Primary documentation checked October 5, 2026. Examples, catalog policies, diagrams and local test fixtures are original to this guide. The lab’s receipts identify its actual runtime; a documentation page’s current version is not a claim about the tested interpreter.
- Unicode Standard Annex #15: Unicode Normalization Forms — canonical and compatibility normalization, including concatenation boundaries.
- Unicode Standard Annex #29: Unicode Text Segmentation — extended grapheme-cluster boundaries and tailoring.
- Unicode Technical Standard #39: Unicode Security Mechanisms — confusables and identifier-related security considerations.
- Python unicodedata documentation — normalization and the runtime Unicode database version.
- Python string operations and casefold — caseless transformations and string behavior.
- Python Unicode HOWTO — code points, encodings and comparison examples.
- Python codec documentation — decoding, encoding and error-handling strategies.
- Python built-in len function — sequence length semantics.
- W3C Character Model for the World Wide Web: String Matching — context for explicit matching policies.
- DeepSeek Chat Completions API documentation — current conversation request structure.

[…] before schema validation and must remain correct for rejected input as well as accepted input. Our Unicode handling guide explores the broader distinction between bytes and […]
[…] the display-name transformation to them inside a sorter could merge identities unexpectedly. The DeepSeek Unicode handling guide explores how to keep transformation purposes […]
[…] Do not decode each incoming chunk as UTF-8 before framing it. A chunk can split a multi-byte text character, and this protocol also permits payloads that are not text at all. First recover the complete payload bytes. If the application defines a payload as UTF-8, decode that completed payload using an explicit error policy. Text normalization is another application decision, discussed separately in our Unicode handling guide. […]