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
之前在文档中有一条关于%运算符将来从语言中删除的声明.此声明已从文档中删除.
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)
我绝对喜欢的format
方法较多,因为它是非常灵活的,可以通过定义很容易地扩展到您的自定义类__format__
或str
或repr
表示.为了保持简单,我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)
高级示例
如果您有自定义类,则可以按如下方式定义它们str
或repr
表示:
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版
一个稍微更具可读性的替代解决方案:
sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)
请注意,它ljust(#ofchars)
使用固定宽度的字符,并且不会像其他解决方案那样动态调整。
(另请注意,在现代 Python 中,字符串加法+
比过去快得多,但如果出于习惯您仍然更喜欢该方法,则可以更换+
为)''.join(...)
随着新的和流行的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字符串更具可读性。