python想右對齊 python右對齊的例項方法

2021-10-11 02:02:18 字數 1851 閱讀 2467

例如,有乙個字典如下:dic = {

"name": "botoo",

"url": "",

"page": "88",

"isnonprofit": "true",

"address": "china",

想要得到的輸出結果如下:name:botoo

首先獲取字典的最大值max(map(len, dic.keys()))

然後使用

str.rjust() 右對齊

或者str.ljust() 左對齊

或者str.center() 居中的方法有序列的輸出。dic = {

"name": "botoo",

"url": "",

"page": "88",

"isnonprofit": "true",

"address": "china",

d = max(map(len, dic.keys())) #獲取key的最大值

for k in dic:

print(k.ljust(d),":",dic[k])

name : botoo

url :

page : 88

isnonprofit : true

address : china

for k in dic:

print(k.rjust(d),":",dic[k])

name : botoo

url :

page : 88

isnonprofit : true

address : china

for k in dic:

print(k.center(d),":",dic[k])

name : botoo

url :

page : 88

isnonprofit : true

address : china

關於 str.ljust()的用法還有這樣的;s = "adc"

s.ljust(20,"+")

'adc+++++++++++++++++'

s.rjust(20)

'adc'

s.center(20,"+")

'++++++++adc+++++++++'

知識點擴充套件:

python中對字串的對齊操作

ljust()、rjust() 和 center()函式分別表示左對齊、右對齊、居中對齊str.ljust(width[, fillchar]):左對齊,width — 指定字串長度,fillchar — 填充字元,預設為空格;

str.rjust(width[, fillchar]):右對齊,width — 指定字串長度,fillchar — 填充字元,預設為空格;

str.center(width[, fillchar]):居中對齊,width — 字串的總寬度,fillchar — 填充字元,預設為空格。test = 'hello world'

print(test.ljust(20))

print(test.ljust(20, '*'))

print(test.rjust(20, '*'))

print(test.center(20, '*'))

print(test.center(20))

#輸出結果如下:

hello world*********

*********hello world

****hello world*****

hello world

python想右對齊 python右對齊的例項方法

例如,有乙個字典如下 dic name botoo url page 88 isnonprofit true address china 想要得到的輸出結果如下 首先獲取字典的最大值max map len,dic.keys 然後使用 str.rjust 右對齊 或者str.ljust 左對齊 或者s...

python想右對齊 python右對齊的例項方法

例如,有乙個字典如下 dic name botoo url page 88 isnonprofit true address china 想要得到的輸出結果如下 首先獲取字典的最大值max map len,dic.keys 然後使用 str.rjust 右對齊 或者str.ljust 左對齊 或者s...

文字左右對齊

leetcode 給定乙個單詞陣列和乙個長度 maxwidth,重新排版單詞,使其成為每行恰好有 maxwidth 個字元,且左右兩端對齊的文字。你應該使用 貪心演算法 來放置給定的單詞 也就是說,盡可能多地往每行中放置單詞。必要時可用空格 填充,使得每行恰好有 maxwidth 個字元。要求盡可能...