# File: strarray.py # Printing a string with the index numbers beneath it # # Matt Bishop, ECS 10, Spring 2014 # # Read in a string # s = 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='') # # 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, end='') print()