文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [2004-08-11 17:35:15]

1. 排列字符串

3.4 Aligning Strings

排列字符串

Credit: Luther Blissett

1.1. 问题 Problem

You want to align strings left, right, or center.

你想把字符串排在左边,右边,中间。

1.2. 解决 Solution

That's what the ljust, rjust, and center methods of string objects are for. Each takes a single argument, the width of the

string you want as a result, and returns the starting string with spaces on either or both sides:

string的ljust, rjust和center方法就是做这个的。每个方法带一个单独的参数,你想要的string的宽度作为一个结果,并且在一端或者两端

返回以空格开始的字符串。

>>> print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|' 
| hej | hej | hej |'. 

1.3. 讨论 Discussion

Centering, left-justifying, or right-justifying text comes up surprisingly often梖or example, when you want to print a simple

report with centered page numbers. Because of this, Python string objects supply this functionality through their methods. 当你想要打印一个页码在中间的简单报告,中间,靠左或者靠右的文本 出现令人惊讶的【乱码】例子。因为这个,python的string对象通过他

们的方法提供了这样的功能

1.4. 参考 See Also

The Library Reference section on string methods; Java Cookbook Recipe 3.5.