Created
January 13, 2026 14:31
-
-
Save Andrielson/1dfe4e6b3d77e8bc9fb80eec6e5ab843 to your computer and use it in GitHub Desktop.
Python Base36 integer to string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def b36(number: int) -> str: | |
| """ | |
| Converts an integer to its string representation in base 36 | |
| (using 0-9 and a-z). | |
| """ | |
| if number == 0: | |
| return "0" | |
| # Define the alphabet for base 36: 0-9 followed by a-z | |
| alphabet = "0123456789abcdefghijklmnopqrstuvwxyz" | |
| # Handle negative numbers | |
| is_negative = number < 0 | |
| number = abs(number) | |
| base36_chars = [] | |
| while number > 0: | |
| number, remainder = divmod(number, 36) | |
| base36_chars.append(alphabet[remainder]) | |
| if is_negative: | |
| base36_chars.append('-') | |
| # The algorithm produces digits in reverse order, so we reverse them back | |
| return ''.join(reversed(base36_chars)) | |
| # --- Usage Examples --- | |
| if __name__ == "__main__": | |
| print(f"0 -> {b36(0)}") # Output: 0 | |
| print(f"10 -> {b36(10)}") # Output: a | |
| print(f"35 -> {b36(35)}") # Output: z | |
| print(f"36 -> {b36(36)}") # Output: 10 | |
| print(f"71 -> {b36(71)}") # Output: 1z | |
| print(f"-1234 -> {b36(-1234)}") # Output: -yuje | |
| print(f"Large -> {b36(123456789)}") # Output: 21i3v9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment