Created
January 26, 2025 23:40
-
-
Save drHyperion451/082419e7d4b66cbcfb987fa3af6edc78 to your computer and use it in GitHub Desktop.
columbo.py: Excel column letters to numbers and vice versa.
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
| import os | |
| def excel_column_to_number(column: str) -> int: | |
| """ | |
| Converts a excel column string to ordinal number. | |
| Ejemplo: "A" -> 1, "B" -> 2, "AA" -> 27 | |
| """ | |
| column = column.upper() # Uppercase letters | |
| result = 0 | |
| for char in column: | |
| # Uses the UTF-8 code for getting the index. | |
| result = result * 26 + (ord(char) - ord('A') + 1) # letters are technically a base26 system... | |
| return result | |
| def number_to_excel_column(number: int) -> str: | |
| """ | |
| Converts a number to the excel column string. | |
| Example: 1 -> "A", 2 -> "B", 27 -> "AA" | |
| """ | |
| result = [] | |
| while number > 0: | |
| number -= 1 | |
| result.append(chr(number % 26 + ord('A'))) | |
| number //= 26 | |
| return ''.join(reversed(result)) | |
| # Ejemplo de uso | |
| if __name__ == "__main__": | |
| # User input and data management | |
| os.system('cls') | |
| try: | |
| while True: | |
| user_input = input("Place column letters or a number: ").strip() | |
| # Check if input is a number or column letters | |
| user_input_parsed = int(user_input) if user_input.isdigit() else user_input.upper() | |
| # Choose automatically the function to use. | |
| if type(userinput_parsed) == int: | |
| print(f" {number_to_excel_column(userinput_parsed)}") | |
| else: | |
| print(f" {excel_column_to_number(userinput_parsed)}") | |
| # Exit with Ctrl + C | |
| except KeyboardInterrupt: | |
| os.system('cls') | |
| quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment