gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:10:01 25 4
gpt4 key购买 nike

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

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

最佳答案

我发现使用 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 字符串:

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'

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

关于python - 如何以固定宽度打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com