如何在Python中左对齐字符串的一部分?

2024-01-11

我想左对齐字符串的右侧部分。我正在编写一个 IRC 机器人的 HELP 命令,我希望描述始终以相同的宽度左对齐:

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

ljust适用于整个字符串,但如何仅对字符串的一部分执行此操作?

这是我当前生成字符串的代码:

format.color( "## ", format.LIME_GREEN ) + self.commands[ cmd ][1].__doc__.format( format.bold( cmd ) ).splitlines()[0].strip()

看看Python的格式规范迷你语言 http://docs.python.org/release/3.3.0/library/string.html#formatspec and printf 风格的字符串格式 http://docs.python.org/3.3/library/stdtypes.html#printf-style-string-formatting.

EXAMPLE:

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

注意format()在 Python 3.0 中引入并向后移植到 Python 2.6,因此如果您使用旧版本,可以通过以下方式实现相同的结果:

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

有必要事先以合理的方式分割字符串。

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中左对齐字符串的一部分? 的相关文章

随机推荐