第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

如何將打印輸出或字符串格式化為固定寬度?

如何將打印輸出或字符串格式化為固定寬度?

瀟湘沐 2019-08-16 15:32:36
如何將打印輸出或字符串格式化為固定寬度?我有這個(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ù)的索引。


查看完整回答
反對 回復(fù) 2019-08-16
?
喵喔喔

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       '


查看完整回答
反對 回復(fù) 2019-08-16
  • 3 回答
  • 0 關(guān)注
  • 1129 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號