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

新手上路,请多包涵

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

 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设置固定长度

原文由 0x90 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

编辑 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() 来获得出现次数。

原文由 mac 发布,翻译遵循 CC BY-SA 4.0 许可协议

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


编辑 2 :在 python3 中,也可以使用 f-strings:

 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 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题