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

2023-12-26

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

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 字符串格式化固定宽度 https://stackoverflow.com/questions/8424474/python-string-formatting-fixed-width

使用python设置固定长度 https://stackoverflow.com/questions/5138062/setting-fixed-length-with-python


我发现使用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'

Edit 1: 正如评论中提到的:0 in '{0: <5}'表示传递给的参数索引str.format().


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

or:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以固定宽度打印字符串? 的相关文章

随机推荐