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

0x9*_*x90 93 python format python-2.7

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

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));
Run Code Online (Sandbox Code Playgroud)

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

因为排列不是相同的长度我想要修复宽度并打印出一个不喜欢这个的好处:

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
Run Code Online (Sandbox Code Playgroud)

我怎么format用来做呢?

我找到了这些帖子,但是它与字母数字字符串不相符:

python字符串格式化固定宽度

用python设置固定长度

0x9*_*x90 178

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

>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'
Run Code Online (Sandbox Code Playgroud)

如果您希望字符串与正确使用对齐>而不是<:

>>> '{0: >5}'.format('ss')
'   ss'
Run Code Online (Sandbox Code Playgroud)

编辑:如评论中所述:0表示格式参数的索引.

  • 我无法再编辑之前的评论,而这需要它.`{<5}`不起作用,但`{:<5}`在没有索引值的情况下工作. (14认同)
  • 这是描述这些格式字符串和其他选项的Python [格式规范迷你语言](https://docs.python.org/2/library/string.html#format-specification-mini-language).为了快速参考,`{0:<5}`中的空格是`[fill]`,```是`[align]`,`5`是`[width]` (9认同)
  • 另外,0表示格式参数的位置,所以你可以做另外两件事:`'{<5}'.format('ss')``'ss'`就像以前一样,但是没有0,相同的事情或''秒{1:<5}和第一个{0:<5}'.格式('ss','sss')``'第二个sss和第一个ss'`所以你可以重新排序甚至输出在单个输出字符串中多次使用相同的变量. (5认同)
  • 那个5可以是一个变量替换`>>>打印宽度20 >>> print"{0:<{width}}".format("ssssss",width = width).split('\n')['ssssss '] >>>` (2认同)
  • 你也可以使用数字,只需按顺序列出变量`width = 10; "{0:<{1}}".format('sss',width)`.或者甚至省略数字''{:<{}}'.format('sss',width)` (2认同)

mac*_*mac 102

编辑2013-12-11 - 这个答案很老.它仍然有效且正确,但是看这个的人应该更喜欢新的格式语法.

你可以使用这样的字符串格式:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
Run Code Online (Sandbox Code Playgroud)

基本上:

  • %字符通知蟒蛇将需要替换的东西令牌
  • s字符通知蟒蛇令牌将是一个字符串
  • 5(你想或任何号码)通知蟒蛇垫空间多达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
Run Code Online (Sandbox Code Playgroud)

侧面注意:只是想知道您是否知道itertools模块的存在.例如,您可以在一行中获得所有组合的列表:

>>> [''.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']
Run Code Online (Sandbox Code Playgroud)

你可以通过combinations结合使用获得出现次数count().

  • 你应该提一下,负数给出左对齐的填充输出; 这对初学者来说几乎不直观. (23认同)
  • 这里有一些在 [Medium](https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e) 上使用 f 字符串进行优雅的固定宽度打印的更多技巧。 (2认同)

joe*_*lom 56

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

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

width=10
'{0: <{width}}'.format('sss', width=width)
Run Code Online (Sandbox Code Playgroud)

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

width=10
'{0: <{1}}'.format('sss', width)
Run Code Online (Sandbox Code Playgroud)

或者甚至省略所有数字以获得最大的,可能是非诡计的隐式,紧凑:

width=10
'{: <{}}'.format('sss', width)
Run Code Online (Sandbox Code Playgroud)

更新2017-05-26

通过在Python 3.6中引入格式化的字符串文字(简称"f-strings"),现在可以使用更简单的语法访问以前定义的变量:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
Run Code Online (Sandbox Code Playgroud)

这也适用于字符串格式

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '
Run Code Online (Sandbox Code Playgroud)


Rya*_*uck 7

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

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

这里,-表示左对齐,而前面的数字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
Run Code Online (Sandbox Code Playgroud)

有关此处文档的更多信息:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations


Mil*_*uss 6

>>> print(f"{'123':<4}56789")
123 56789
Run Code Online (Sandbox Code Playgroud)


Abu*_*oeb 6

我发现以固定宽度打印字符串或用空格填充Python字符串ljust()非常有用。rjust()

一个例子

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

# expected output  
   123.00
123456.89
Run Code Online (Sandbox Code Playgroud)

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

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

预期输出

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
Run Code Online (Sandbox Code Playgroud)

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


Nir*_*ake 5

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

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("__________________________________________________________________")
Run Code Online (Sandbox Code Playgroud)

这将打印

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________
Run Code Online (Sandbox Code Playgroud)