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

2024-04-26 18:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: of字符串inforstringprefixvalueresult
3条回答

最初是作为@0x90答案的编辑发布的,但由于偏离了帖子的初衷而被拒绝,建议作为评论或答案发布,所以我在这里包括了简短的评论。

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

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

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

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

或者甚至为最大的、潜在的非pythonical隐式紧性忽略所有数字:

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       '

我发现使用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表示传递给str.format()的参数索引。

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

旁注:只是想知道您是否知道^{} 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()结合使用来获得出现的次数。

相关问题 更多 >