简体   繁体   中英

print out tiles from command line argument

I need to print out tiles based on command line arguments in which first argument is the width and second is the name. for example:

$ python tile.py 5 tommy
------+|+------
---+|++|++|+---
-----TOMMY-----
---+|++|++|+---
------+|+------

or

$ python tile.py 7 Samuel 
---------+|+---------
------+|++|++|+------
---+|++|++|++|++|+---
--------SAMUEL-------
---+|++|++|++|++|+---
------+|++|++|+------
---------+|+---------

as there are some restriction: width can only be odd, and the length of the name cannot exceed 3*width.

I am confused how to do the vertical part as it can be 5, 7, or more layers

import sys
a = int(sys.argv[1])
if a%2==0:
    print('Error: tile height must be an odd number')
else:
    if len(sys.argv[2])>(3*a):
        print('Error: name must fit within {} characters'.format(3*a))
    else:
        print('-'*((3*a-3)/2)+'+-+'+'-'*((3*a-3)/2))
        print('-'*((3*a-9)/2))

You can use the string function str.center to simplify the padding. Other than that you just use a loop to count up and then down, leveraging pythons str.join and * operator on lists:

#        Growing width       Name    Shrinking width
widths = list(range(a//2)) + [-1] + list(reversed(range(a//2)))
for k in widths:
    # Print name if we're halfway there
    if k == -1: 
        # Print name in uppercase, centered over 3*a characters, padded with '-'
        print(name.upper().center(3*a,'-'))
    else:
        # Repeat '+|+' 1+2k number of times, 
        # join with nothing in between and center, padding with '-'
        print("".join(["+|+"]*(1+2*k)).center(3*a,'-'))


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM