Advertisement
acclivity

pyFeetInches-Strings2Decimals

Feb 6th, 2021 (edited)
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # Convert Feet and Inches to Feet decimals
  2. # Mike Kerry - Feb 2021 - [email protected]
  3.  
  4. hlist = ["Height", "3 ft 4in", "4ft 1 in", "4ft", "3ft 9in", "3.5ft", "4ft 3 in", "3ft 7in"]
  5.  
  6. total_inches = 0.0          # Accumulator for sum of heights in inches
  7. valid_heights = 0           # Count of valid height strings found
  8.  
  9. for hs in hlist[1:]:        # Process each cell except the first (which contains "height")
  10.     x = hs.find("ft")       # we expect to find the string "ft" in every cell
  11.     if x < 0:
  12.         print("Invalid cell: ", hs)
  13.         continue
  14.  
  15.     valid_heights += 1      # Count one valid height string
  16.     hs1 = hs[:x].strip()    # extract everything before "ft" and strip off any leading and trailing spaces
  17.     feet = float(hs1)       # what's left can now be converted to a float value (no matter if integer or float)
  18.  
  19.     # Now extract any inches
  20.     inches = 0              # start by assuming there are no inches specified
  21.     y = hs.find("in")
  22.     if y > 0:               # was "in" found? (if not, y will be -1, and inches stays at zero)
  23.         hs2 = hs[x+2:y].strip()     # Extract everything between "ft" and "in" and strip it
  24.         inches = float(hs2)         # What's left can now be converted to inches as a float
  25.  
  26.     inches += feet * 12             # Compute total inches for one student
  27.     total_inches += inches          # compute sum of heights for all students in inches
  28.  
  29. print("The average student height is {:.3f} inches".format(total_inches / valid_heights))
  30.  
  31. total_feet = total_inches / 12.0    # convert to feet and decimals
  32. print("The average student height is {:.1f} feet".format(total_feet / valid_heights))
  33.  
  34. # Output:
  35. # The average student height is 45.429 inches
  36. # The average student height is 3.8 feet
  37.  
  38.  
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement