# File: str_array.py # Printing a string with the index numbers beneath it # # Matt Bishop, MHI 289I, Winter 2018 # # Read in a string # s = raw_input("Enter string: ") # # Count the number of characters # the number of digits in the number of characters is how # wide to make each slot # digits = len(str(len(s))) # # Print a blank line for style # print '' # # This looks ugly but it's really easy # Suppose there are 123 characters in the input # we then want a slot of len("123")+1 or 4 spaces # this constructs a format string of %4d # the first "%%" is "%", then comes "%d" (digits, # see above), then the following "d" # fmt = "%%%dd |" % digits # # print index values; note we use the above format string # for pos in range(len(s)): print fmt % pos, # # End the line # print '' # # Now we do what we did before, but to make space # for printing a character; note the width is the # same as for the index list, above (see final "s" # in the format string) # fmt = "%%%ds |" % digits # # Now print the character at each index # for ch in s: print fmt % ch, print