如何將打印輸出或字符串格式化為固定寬度?我有這個(gè)代碼(在字符串中打印所有排列的出現(xiàn))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));我想打印字符串變量中的所有排列事件。因?yàn)榕帕胁皇窍嗤拈L度我想要修復(fù)寬度并打印出一個(gè)不喜歡這個(gè)的好處:value a - num of occurrences = 1value ab - num of occurrences = 1value abc - num of occurrences = 1value b - num of occurrences = 1value bc - num of occurrences = 1value bcd - num of occurrences = 1value c - num of occurrences = 1value cd - num of occurrences = 1value d - num of occurrences = 1我怎么format用來做呢?
3 回答

holdtom
TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
我發(fā)現(xiàn)使用str.format更優(yōu)雅:
>>> '{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表示格式參數(shù)的索引。

喵喔喔
通過在Python 3.6中引入格式化的字符串文字(簡稱“f-strings”),現(xiàn)在可以使用更簡單的語法訪問以前定義的變量:
TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
因偏離帖子的原始意圖而被拒絕,并建議發(fā)表評論或回答,所以我在這里寫了一篇簡短的文章。
除了@ 0x90的答案之外,通過使用寬度變量(根據(jù)@ user2763554的注釋),可以使語法更加靈活:
width=10'{0: <{width}}'.format('sss', width=width)
此外,您可以通過僅使用數(shù)字并依賴傳遞給的參數(shù)的順序來使此表達(dá)式更簡潔format
:
width=10'{0: <{1}}'.format('sss', width)
或者甚至遺漏所有數(shù)字,以獲得最大的,可能非韻律隱含的緊湊性:
width=10'{: <{}}'.format('sss', width)
通過在Python 3.6中引入格式化的字符串文字(簡稱“f-strings”),現(xiàn)在可以使用更簡單的語法訪問以前定義的變量:
>>> name = "Fred">>> f"He said his name is {name}."'He said his name is Fred.'
這也適用于字符串格式
>>> width=10>>> string = 'sss'>>> f'{string: <{width}}''sss '
添加回答
舉報(bào)
0/150
提交
取消