| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- def validate_rut(rut):
- """
- Validates a Chilean RUT (Rol Único Tributario).
-
- Args:
- rut (str): The RUT to validate, formatted as '12345678-9'.
-
- Returns:
- bool: True if the RUT is valid, False otherwise.
- """
- rut = rut.replace(".", "").strip()
- if not rut or '-' not in rut:
- return False
-
- try:
- body, dv = rut.split('-')
- body = int(body)
- dv = dv.upper()
- except ValueError:
- return False
-
- if len(str(body)) < 7 or len(str(body)) > 8:
- return False
-
- # Calculate the expected DV
- total = 0
- factor = 2
- for digit in reversed(str(body)):
- total += int(digit) * factor
- factor = factor + 1 if factor < 7 else 2
-
- expected_dv = str((11 - (total % 11)) % 11)
- if expected_dv == '10':
- expected_dv = 'K'
-
- return dv == expected_dv
- if __name__ == "__main__":
- # Example usage
- print(validate_rut("1234567-10")) # Should return False, invalid
- print(validate_rut("21382334-5")) # Should return True, validity
- print(validate_rut("21975985-1")) # Should return True, validity
|