Python 如何左对齐固定宽度的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12684368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to left align a fixed width string?
提问by John Mee
I just want fixed width columns of text but the strings are all padded right, instead of left!!?
我只想要固定宽度的文本列,但字符串都是向右填充的,而不是向左填充!!?
sys.stdout.write("%6s %50s %25s\n" % (code, name, industry))
produces
产生
BGA BEGA CHEESE LIMITED Food Beverage & Tobacco
BHP BHP BILLITON LIMITED Materials
BGL BIGAIR GROUP LIMITED Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED Energy
but we want
但我们想要
BGA BEGA CHEESE LIMITED Food Beverage & Tobacco
BHP BHP BILLITON LIMITED Materials
BGL BIGAIR GROUP LIMITED Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED Energy
采纳答案by Matthew Trevor
You can prefix the size requirement with -to left-justify:
您可以在尺寸要求前加上-左对齐:
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
回答by Joran Beasley
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
on a side note you can make the width variable with *-s
在旁注中,您可以使用 *-s
>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple something '
回答by Rohit Jain
Use -50%instead of +50%They will be aligned to left..
使用-50%而不是+50%它们将向左对齐..
回答by Marwan Alsabbagh
This version uses the str.formatmethod.
此版本使用str.format方法。
Python 2.7 and newer
Python 2.7 及更新版本
sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))
Python 2.6 version
Python 2.6 版本
sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))
UPDATE
更新
Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been removed from the docs.
以前在文档中有关于 % 运算符将来会从语言中删除的声明。此声明已从文档中删除。
回答by Nick Sweeting
A slightly more readable alternative solution:sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)
一个更易读的替代解决方案:sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)
Note that ljust(#ofchars)uses fixed width characters and doesn't dynamically adjust like the other solutions.
请注意,ljust(#ofchars)使用固定宽度的字符并且不会像其他解决方案那样动态调整。
回答by codeRunner89
This one worked in my python script:
这个在我的python脚本中工作:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
回答by user1767754
I definitely prefer the formatmethod more, as it is very flexible and can be easily extended to your custom classes by defining __format__or the stror reprrepresentations. For the sake of keeping it simple, i am using printin the following examples, which can be replaced by sys.stdout.write.
我绝对更喜欢这种format方法,因为它非常灵活,可以通过定义__format__orstr或repr表示轻松扩展到您的自定义类。为了简单起见,我print在以下示例中使用,可以替换为sys.stdout.write.
Simple Examples:alignment / filling
简单示例:对齐/填充
#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido")) # 'Guido '
print("{0:>10}".format("Guido")) # ' Guido'
print("{0:^10}".format("Guido")) # ' Guido '
We can add next to the alignspecifies which are ^, <and >a fill character to replace the space by any other character
我们可以添加旁边align这是指定^,<并>填充字符使用任何其他字符来代替空间
print("{0:.^10}".format("Guido")) #..Guido...
Multiinput examples:align and fill many inputs
多输入示例:对齐和填充多个输入
print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'
Advanced Examples
高级示例
If you have your custom classes, you can define it's stror reprrepresentations as follows:
如果您有自定义类,则可以按如下方式定义它str或repr表示:
class foo(object):
def __str__(self):
return "...::4::.."
def __repr__(self):
return "...::12::.."
Now you can use the !s(str) or !r(repr) to tell python to call those defined methods. If nothing is defined, Python defaults to __format__which can be overwritten as well.
x = foo()
现在你可以使用!s(str) 或!r(repr) 来告诉 python 调用那些定义的方法。如果未定义任何内容,Python 默认 __format__也可以覆盖它。x = foo()
print "{0!r:<10}".format(x) #'...::12::..'
print "{0!s:<10}".format(x) #'...::4::..'
Source: Python Essential Reference, David M. Beazley, 4th Edition
来源:Python 基本参考,David M. Beazley,第 4 版
回答by Ketan
With the new and popular f-stringsin Python 3.6, here is how we left-align say a string with 16 padding length:
随着新的和流行的F-字符串中的Python 3.6,这里是我们如何左对齐说有16个填充长度的字符串:
string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow ..
If you have variable padding length:
如果您有可变的填充长度:
k = 20
print(f"{string:<{k}}..")
Stack Overflow ..
f-stringsare more compact.
f 弦更紧凑。

