如何左对齐固定宽度的字符串?

Joh*_*Mee 58 python string-formatting

我只想要固定宽度的文本列,但字符串都填充正确,而不是左边!!?

 sys.stdout.write("%6s %50s %25s\n" % (code, name, industry))
Run Code Online (Sandbox Code Playgroud)

产生

BGA                                BEGA CHEESE LIMITED   Food Beverage & Tobacco
BHP                               BHP BILLITON LIMITED                 Materials
BGL                               BIGAIR GROUP LIMITED Telecommunication Services
BGG           BLACKGOLD INTERNATIONAL HOLDINGS LIMITED                    Energy
Run Code Online (Sandbox Code Playgroud)

但我们想要

BGA BEGA CHEESE LIMITED                                Food Beverage & Tobacco
BHP BHP BILLITON LIMITED                               Materials
BGL BIGAIR GROUP LIMITED                               Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED           Energy
Run Code Online (Sandbox Code Playgroud)

Mat*_*vor 107

您可以使用-left-justify作为大小要求的前缀:

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
Run Code Online (Sandbox Code Playgroud)


Mar*_*agh 41

此版本使用str.format方法.

Python 2.7及更新版本

sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))
Run Code Online (Sandbox Code Playgroud)

Python 2.6版本

sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))
Run Code Online (Sandbox Code Playgroud)

UPDATE

之前在文档中有一条关于%运算符将来从语言中删除的声明.此声明已从文档中删除.

  • 旧的风格不再被弃用,我相信:http://bugs.python.org/issue14123 (5认同)
  • @Matthew - Disinformation是错误的信息,意图误导.我怀疑Marwan有这样的意图. (4认同)
  • 您正在查看文档的不同部分.[旧字符串格式]部分(http://docs.python.org/py3k/tutorial/inputoutput.html#old-string-formatting)仍然存在于3.3文档中,它位于教程部分而非库引用中.并且声明"这种旧的格式化格式最终将从语言中删除"仍然存在. (2认同)

Jor*_*ley 26

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
Run Code Online (Sandbox Code Playgroud)

在旁注上你可以使宽度变量 *-s

>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple                    something                     '
Run Code Online (Sandbox Code Playgroud)


Roh*_*ain 9

使用-50%而不是+50%他们将左对齐..


use*_*754 8

我绝对喜欢的format方法较多,因为它是非常灵活的,可以通过定义很容易地扩展到您的自定义类__format__strrepr表示.为了保持简单,我print在以下示例中使用,可以替换为sys.stdout.write.

简单示例:对齐/填充

#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido"))    # 'Guido     '
print("{0:>10}".format("Guido"))    # '     Guido'
print("{0:^10}".format("Guido"))    # '  Guido   '
Run Code Online (Sandbox Code Playgroud)

我们可以在align指定的旁边添加^,<以及>用任何其他字符替换空格的填充字符

print("{0:.^10}".format("Guido"))    #..Guido...
Run Code Online (Sandbox Code Playgroud)

多输入示例:对齐并填充许多输入

print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'
Run Code Online (Sandbox Code Playgroud)

高级示例

如果您有自定义类,则可以按如下方式定义它们strrepr表示:

class foo(object):
    def __str__(self):
        return "...::4::.."

    def __repr__(self):
        return "...::12::.."
Run Code Online (Sandbox Code Playgroud)

现在你可以使用!s(str)或!r(repr)来告诉python调用那些定义的方法.如果没有定义任何内容,Python默认 __format__也可以覆盖.x = foo()

print "{0!r:<10}".format(x)    #'...::12::..'
print "{0!s:<10}".format(x)    #'...::4::..'
Run Code Online (Sandbox Code Playgroud)

来源:Python Essential Reference,David M. Beazley,第4版


Nic*_*ing 6

一个稍微更具可读性的替代解决方案:
sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)

请注意,它ljust(#ofchars)使用固定宽度的字符,并且不会像其他解决方案那样动态调整。

(另请注意,在现代 Python 中,字符串加法+比过去快得多,但如果出于习惯您仍然更喜欢该方法,则可以更换+为)''.join(...)


Ket*_*tan 5

随着新的和流行的F-字符串的Python 3.6,这里是我们如何左对齐说有16个填充长度的字符串:

string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow  ..
Run Code Online (Sandbox Code Playgroud)

如果填充长度可变:

k = 20
print(f"{string:<{k}}..")
Stack Overflow      .. 
Run Code Online (Sandbox Code Playgroud)

f字符串更具可读性。

  • 您还可以将方向字符 `&gt;`、`&lt;`、`^` 等作为变量,因此在 `a="&lt;"` 之后,您可以使用:`f"{string:{a}{k} ”` (2认同)