this piece of code is driving me crazy. I'm trying to print a help list for a program I'm writing. So I define a dictionary, where the keys are the words that the user might want to be clarified and the values are the descriptions of the words. Then I use a for... in...
loop to print it all. To put it simple:
ERROR = '\x1B[1;31m ERROR!! \x1B[0m'
WARNING = '\x1B[1;33m WARNING! \x1B[0m'
SUCCESS = '\x1B[1;32m Operation successful! \x1B[0m'
ABORTED = '\x1B[1;33m Operation aborted! \x1B[0m'
help_descriptions = {'\x1B[34m NUMBERS \x1B[0m':'are the options you can take.',\
ERROR:'means you ran into and error and the program can\'t go on.',\
WARNING:'means that the data you entered might cause problems.',\
SUCCESS:'means that no run-time errors where encoutered.',\
ABORTED:'means you aborted a previous option, deleting\n the data associated.'}
def HelpMe():
print(70 * '~')
print(' HELP')
print(70 * '~')
for key in help_descriptions.keys():
print('%10s %s' % (key, help_descriptions.get(key)))
print(70 * '~')
The only thing that doesn't work is the %10s
to开发者_JS百科ken. I mean, it does print the value of the key, but it does not puts extra spaces if needed. I've tried to run in an interactive section this piece of code
print('%10s' % 'foo')
and the output is right.
Does any of you have an idea of how make it work?
Additional info: I'm running Python 3 on a Linux machine running Ubuntu 11.04. This code is part of a custom module I've written to store some static text or simple functions that print text. So I import this module in the main application, it is not stand-alone.
Thank you in advance.
The problem is that those are at least 10 characters long: remember, the ANSI escape characters count. You could do any of the following:
- Increase the field width until you get the width you want (since all of them seem to contain the same number of escape characters, this might work).
- Strip the escape characters and use the result for padding.
- Pad the labels (like "WARNING!") to the correct field width before adding the escape characters.
Any of these should achieve the desired effect.
精彩评论