3

I want to left justify the right part of a string. I am writing an IRC Bot's HELP command and I want the description to be left justified at the same width throughout:

List of commands:
## !          Say a Text
## execute    Execute an IRC command
## help       Help for commands

ljust works for a whole string, but how do I do this on a part of a string only?

This is my current code for generating the string:

format.color( "## ", format.LIME_GREEN ) + self.commands[ cmd ][1].__doc__.format( format.bold( cmd ) ).splitlines()[0].strip()
1
  • Split the strings in the relevant parts, ljust the ones you want, and join the pieces. Commented Dec 10, 2012 at 21:00

2 Answers 2

3

Have a look at Python's Format Specification Mini-Language and printf-style String Formatting.

EXAMPLE:

>>> '{:<20} {}'.format('## execute', 'Execute an IRC command')
'## execute           Execute an IRC command'

Note that format() was introduced in Python 3.0 and backported to Python 2.6, so if you are using an older version, the same result can be achieved by:

>>> '%-20s %s' % ('## execute', 'Execute an IRC command')
'## execute           Execute an IRC command'

It's necessary to split the strings in a sensible manner beforehand.

EXAMPLE:

>>> '{:<20} {}'.format(*'{0} <COMMAND>: Help for <command>'.split(': '))
'{0} <COMMAND>        Help for <command>'

>>> '%-20s %s' % tuple('{0} <COMMAND>: Help for <command>'.split(': '))
'{0} <COMMAND>        Help for <command>
Sign up to request clarification or add additional context in comments.

2 Comments

this works for that list, but how do I go around formatting this: "{0} <COMMAND>: Help for <command>"
okay, your second one works that perfect that I switched to yours for compactibility. I didn't now the .format() engine was this powerfull!
0

You rightly mention str.ljust, so it's just a case of splitting your string as appropriate and applying it to the 'left' part. E.g:

>>> parts = "## ! Say a Text".split(" ", 2)
>>> " ".join(parts[:2]).ljust(20)+parts[2]
'## !                Say a Text'

Obviously, it may be better to do this before you start joining the string for simplicity.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.