NIE
Número de Identidad de Extranjero (NIE)¶
Overview¶
The NIE identifies foreign residents. It resembles the DNI but starts with a prefix letter X, Y, or Z, followed by seven digits and the familiar control letter. Each prefix maps to a digit so that NIEs share the same control-letter logic as DNIs.
Algorithm Walkthrough¶
- Canonicalise by uppercasing the value; inputs must already be the correct length without separators.
- Format check against the regular expression
[XYZ]\d{7}[A-Z]. - Translate the prefix to a digit using
{"X": "0", "Y": "1", "Z": "2"}and concatenate it with the seven digits to create an eight-digit number. - Compute the remainder of that number divided by 23.
- Map to the control letter using the same
TRWAGMYFPDXBNJZSQVHLCKEsequence used for DNIs. - Validate that the calculated letter matches the provided letter.
Worked Examples¶
X1234567L: prefixX→0, number01234567, remainder11, expected letterL.Y1234567X: prefixY→1, number11234567, remainder21, expected letterX.Z1234567R: prefixZ→2, number21234567, remainder18, expected letterR.
Formal Specification¶
- Input must be exactly 9 ASCII characters.
- Character 1:
X,Y, orZ. - Characters 2–8: digits
0-9. - Character 9: uppercase letter
A-Z. - Let
prefix_map = {"X": "0", "Y": "1", "Z": "2"}. - Let
n = int(prefix_map[char1] + chars2to8). - Let
letters = "TRWAGMYFPDXBNJZSQVHLCKE". - Valid iff
letters[n % 23] == character9.
Using the Library¶
from spanish_nif import NIE, InvalidNIE
nie = NIE("X1234567L")
assert nie.prefix == "X"
assert nie.number == 1234567 # numeric value used for the control-letter calculation
if not NIE.is_valid("x1234567l"): # uppercased internally, so this returns True
raise RuntimeError("Unexpected validation failure")
Generating Sample NIEs¶
The NIE.random() helper returns valid identifiers for fixtures and demos:
from spanish_nif import NIE
nie = NIE.random()
assert nie[0] in {"X", "Y", "Z"}
assert len(nie) == 9
For reproducible sequences, provide your own random.Random instance.
Official References¶
- Orden INT/2058/2008, de 14 de julio, sobre determinados documentos de identidad y de viaje — el anexo II detalla la estructura del NIE, los prefijos
X/Y/Zy la letra de control. - Agencia Tributaria: Número de Identidad de Extranjero (NIE) — guía oficial sobre asignación y composición del NIE.