rut.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. def validate_rut(rut):
  2. """
  3. Validates a Chilean RUT (Rol Único Tributario).
  4. Args:
  5. rut (str): The RUT to validate, formatted as '12345678-9'.
  6. Returns:
  7. bool: True if the RUT is valid, False otherwise.
  8. """
  9. rut = rut.replace(".", "").strip()
  10. if not rut or '-' not in rut:
  11. return False
  12. try:
  13. body, dv = rut.split('-')
  14. body = int(body)
  15. dv = dv.upper()
  16. except ValueError:
  17. return False
  18. if len(str(body)) < 7 or len(str(body)) > 8:
  19. return False
  20. # Calculate the expected DV
  21. total = 0
  22. factor = 2
  23. for digit in reversed(str(body)):
  24. total += int(digit) * factor
  25. factor = factor + 1 if factor < 7 else 2
  26. expected_dv = str((11 - (total % 11)) % 11)
  27. if expected_dv == '10':
  28. expected_dv = 'K'
  29. return dv == expected_dv
  30. if __name__ == "__main__":
  31. # Example usage
  32. print(validate_rut("1234567-10")) # Should return False, invalid
  33. print(validate_rut("21382334-5")) # Should return True, validity
  34. print(validate_rut("21975985-1")) # Should return True, validity