Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. # "Serial/Ordinal" number conversion
  2. ordinal_endings = ["st", "nd", "rd", "th"]
  3. BASE_CHAR_POS = ord('a') - 1
  4.  
  5. def get_last_digit(num):
  6.     return num%10
  7.  
  8. def get_char_pos(char):
  9.     # Conditional expression will check whether or not char
  10.     # is a string that needs to be converted into its ascii
  11.     # value, or if the ascii value has already been passed.
  12.     return (ord(char) if isinstance(char, str) else char) - BASE_CHAR_POS
  13.  
  14. def get_ordinal(num):
  15.     last_digit = get_last_digit(num)
  16.  
  17.     ordinal = str(num)
  18.     ordinal_suffix = None
  19.  
  20.     # Specific cases for "teens"
  21.     if (num > 10 and num < 21):
  22.         ordinal_suffix = ordinal_endings[3]
  23.     elif last_digit >= 1 and last_digit <= 3:
  24.         ordinal_suffix = ordinal_endings[last_digit-1]
  25.     else:
  26.         # For numbers with last digit 0 or =/= 1,2,3
  27.         ordinal_suffix = ordinal_endings[3]
  28.  
  29.     return ordinal + ordinal_suffix
  30.  
  31. while True:
  32.     try:
  33.         # Passing input to ord is a way we can type check
  34.         # for a character, without doing it explicitly.
  35.         input_char_val = ord(input("Enter a character:> "))
  36.     except:
  37.         continue
  38.  
  39.     char_pos = get_char_pos(input_char_val)
  40.     print("The ordinal position of this character is:", get_ordinal(char_pos))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement