William Fowler
William Fowler

Reputation: 31

Name tag creation module

Hello I'm currently writing a game in python and at one point it puts the user's name into a name tag, however I've run into a problem.

e.g.

def name_tag(name):
printf("____________")
printf("|## {} ##|".format(name))
printf("|__________|")

Assuming it works

___________
|##Sarah##|
|_________|

It won't work for a word that has a length longer or shorter than "Sara"

___________
|##Joshua##|
|_________|

This is because the extra/less letters push the border in and out. Does anyone know how to fix this?

Upvotes: 0

Views: 789

Answers (1)

dylrei
dylrei

Reputation: 1736

You could just adjust the length of the top and bottom lines, as follows. Just to eliminate one possible set of problems, I've also clipped the max length of the name at 80.

def name_tag(name):
    name_len = min(len(name), 80)
    print '-' * (name_len + 8)
    print '|## {} ## |'.format(name[:name_len])
    print '-' * (name_len + 8)


>>> name_tag('Sarah')
-------------
|## Sarah ## |
-------------
>>> name_tag('JT')
----------
|## JT ## |
----------
>>> name_tag('An improbably long name for an example')
----------------------------------------------
|## An improbably long name for an example ## |
----------------------------------------------

Edit: adapting the above to match the formatting in the code you posted:

def name_tag(name):
    name_len = min(len(name), 80)
    print '_' * (name_len + 8)
    print '|## {} ## |'.format(name[:name_len])
    print '|{}|'.format('_' * (name_len + 6))

Upvotes: 1

Related Questions