如何在固定宽度下打印字符串?

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

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 字符串

使用 python 设置固定长度

365665 次浏览

EDIT 2013-12-11 -这个答案很老了。它仍然是有效和正确的,但人们看到这应该更喜欢的 新的格式语法

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

>>> 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

旁注: 只是想知道你是否知道 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']

通过使用 combinationscount(),您可以得到出现的次数。

我发现使用 str.format要优雅得多:

>>> '{0: <5}'.format('s')
's    '
>>> '{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'

编辑1 : 正如注释中提到的: '{0: <5}'中的 0表示传递给 str.format()的参数的索引。


编辑2 : 在 python3中也可以使用 f 字符串:

sub_str='s'
for i in range(1,6):
s = sub_str*i
print(f'{s:>5}')
    

'    s'
'   ss'
'  sss'
' ssss'
'sssss'

或:

for i in range(1,5):
s = sub_str*i
print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

值得注意的是,在上面的一些地方,增加了 ' '(单引号)来强调打印字符串的宽度。

最初是作为@0x90的回答的编辑发布的,但是因为偏离了原来的意图而被拒绝,建议作为评论或回答发布,所以我在这里包括了简短的评论。

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

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

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

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

或者甚至省略所有的数字,以获得最大的、可能非 Python 隐式的紧致性:

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

更新2017-05-26

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

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

这也适用于字符串格式设置

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

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

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

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

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("__________________________________________________________________")

这个会打印出来

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

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

举个例子

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更改为排列字符串的最高长度。