Search code examples
pythonpython-3.xtext-alignmentascii-art

Line up printed text underneath a printed image?


So I've got an assignment for my CS class. It's very basic but I'm interested in this class and I wanted to make the code a bit "fancier" I guess. I've been googling to see how I can print the results with some ASCII art and some user inputs below. I've got the art down, and the input parts nearly ready!

I want them to line up nicely. I want to limit the user input to a certain amount of characters for the first name input, and then have the second one print in a specific place. I hope what I'm typing makes sense!

For context, the assignment is:

Given a person's name, their age, the name of their dog and their dog’s age (in human years), display a picture, similar to the following, with the names displayed and the ages of both the person and the dog in “dog years” printed at the bottom of the picture.

So the code I have so far goes like this.....:

#Assignment #1, I love ascii art so I hope you don't mind that I changed things up a little!
InputName = input("Please enter your name: ")
InputHumanAge = int(input("Please enter your age: "))

DogName = input("What is your dog's name? ")
InputDogAge = int(input("How old is your dog in human years? "))

HumanYears = InputHumanAge*7
DogYears = InputDogAge*7

print('      ________ ')
print('    /          \             ___       ___ ')
print('  /             \           |   \_____/   | ')
print(' / /  \______\__\ \        /  |\/     \/|  \ ')
print(' | |  O      O |  |        \_/ | /\ /\ | \_/ ')
print(' / |     __    /  |            |_\/ \/_| ')
print(' \  \ _______ /  /            /   \o/   \ ')
print('  |   __|  |__  |             \___/O\___/ ')
print('  '+ InputName +'                                '+ DogName +' ')
print('  '+ str(HumanYears) +'                       '+ str(DogYears) +' ')

My problem right now is that the text underneath the dog doesn't line up the way I want. Any help is appreciated <3 Thank you!


Solution

  • If you are using Python 3.6+, you can use f-strings like this:

    print(f'  {InputName:<28s}{DogName}')
    print(f'  {HumanYears:<28d}{DogYears}') 
    

    Instead of:

    print('  '+ InputName +'                                '+ DogName +' ')
    print('  '+ str(HumanYears) +'                       '+ str(DogYears) +' ')
    

    To move dog's attributes left or right, decrease or increase, respectively, that 28 value in the f-strings.

    That <28s means align on left and fill right with spaces up to a 28 characters wide. Ditto for <28d but for integers.