如何将打印输出或字符串格式化为固定宽度?

时间:2011-12-09 19:10:55

标签: python python-2.7 format

我有这段代码(在字符串中打印所有排列的出现)

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result    

el =[];

string = "abcd"
for b in splitter("abcd"):
    el.extend(b);

unique =  sorted(set(el));

for prefix in unique:
    if prefix != "":
        print "value  " , prefix  , "- num of occurrences =   " , string.count(str(prefix));

我想打印字符串变量中的所有排列事件。

由于排列的长度不一样,我想修改宽度并将其打印成一个不喜欢这个的好颜色:

value   a - num of occurrences =    1
value   ab - num of occurrences =    1
value   abc - num of occurrences =    1
value   b - num of occurrences =    1
value   bc - num of occurrences =    1
value   bcd - num of occurrences =    1
value   c - num of occurrences =    1
value   cd - num of occurrences =    1
value   d - num of occurrences =    1

如何使用format来执行此操作?

我找到了这些帖子,但是字母数字字符串不太合适:

python string formatting fixed width

Setting fixed length with python

7 个答案:

答案 0 :(得分:165)

我发现使用str.format更优雅:

>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

如果您希望字符串与正确对齐,请使用>代替<

>>> '{0: >5}'.format('ss')
'   ss'

编辑: 如注释中所述:0表示format参数的索引。

答案 1 :(得分:93)

编辑2013-12-11 - 这个答案非常陈旧。它仍然有效且正确,但是看这个的人应该更喜欢new format syntax

您可以像这样使用string formatting

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

基本上:

  • %字符通知python它必须用某些东西代替令牌
  • s字符通知python令牌将是一个字符串
  • 5(或您想要的任何数字)通知python用最多5个字符的空格填充字符串。

在您的具体情况下,可能的实现可能如下所示:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE注意:只是想知道您是否知道itertools module的存在。例如,您可以在一行中获得所有组合的列表:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

您可以将combinationscount()结合使用来获取发生次数。

答案 2 :(得分:47)

最初是作为@ 0x90答案的编辑发布的,但它因偏离帖子的原始意图而被拒绝,并建议发表评论或回答,所以我在这里写了一篇简短的文章。 / em>的

除了来自@ 0x90的答案之外,通过使用宽度变量(根据@ user2763554的评论),可以使语法更加灵活:

width=10
'{0: <{width}}'.format('sss', width=width)

此外,您可以通过仅使用数字并依赖传递给format的参数的顺序来使此表达式更简洁:

width=10
'{0: <{1}}'.format('sss', width)

甚至可以省略所有数字,以获得最大的,可能非韵律隐含的紧凑性:

width=10
'{: <{}}'.format('sss', width)

更新2017-05-26

在Python 3.6中使用the introduction of formatted string literals(简称“f-strings”),现在可以使用更简单的语法访问以前定义的变量:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

这也适用于字符串格式

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '

答案 3 :(得分:8)

format绝对是最优雅的方式,但是你不能在python的logging模块中使用它,所以这里是你如何使用%格式来实现的:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

此处,-表示左对齐,s之前的数字表示固定宽度。

一些示例输出:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

此处文档的详细信息:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

答案 4 :(得分:4)

>>> print(f"{'123':<4}56789")
123 56789

答案 5 :(得分:2)

我发现 ljust()rjust() 对于以固定宽度或 fill out a Python string with spaces 打印字符串非常有用。

一个例子

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89

对于您的情况,您的情况使用 fstring 打印

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")

预期输出

value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1

您可以将 3 更改为排列字符串的最大长度。

答案 6 :(得分:0)

当您要在一个打印语句中打印多个元素时,这将有助于保持固定长度

25s设置25个空格的字符串,默认情况下将其对齐

5d格式化保留5个空格的整数,默认情况下右对齐

members=["Niroshan","Brayan","Kate"]
print("__________________________________________________________________")
print('{:25s} {:32s} {:35s} '.format("Name","Country","Age"))
print("__________________________________________________________________")
print('{:25s} {:30s} {:5d} '.format(members[0],"Srilanka",20))
print('{:25s} {:30s} {:5d} '.format(members[1],"Australia",25))
print('{:25s} {:30s} {:5d} '.format(members[2],"England",30))
print("__________________________________________________________________")

25s设置25个空格的字符串,默认情况下将其对齐

5d格式化保留5个空格的整数,默认情况下右对齐

这将打印

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________