For example, there is a dictionary as follows:
dic ={"name":"botoo","url":"//www.zalou.cn","page":"88","isNonProfit":"true","address":"china",}
The desired output is as follows:
name:botoo
url:https:www.zalou.cn
page:88
isNonProfit:ture
address:china
First get the maximum value of the dictionary max(map(len, dic.keys()))
Then use
Str.rjust() align right
or
Str.ljust() left justify
or
Str.center() The center method has sequential output.
dic ={"name":"botoo","url":"//www.zalou.cn","page":"88","isNonProfit":"true","address":"china",}
d =max(map(len, dic.keys())) #Get the maximum value of key
for k in dic:print(k.ljust(d),":",dic[k])
name : botoo
url ://www.zalou.cn
page :88
isNonProfit :true
address : china
for k in dic:print(k.rjust(d),":",dic[k])
name : botoo
url ://www.zalou.cn
page :88
isNonProfit :true
address : china
for k in dic:print(k.center(d),":",dic[k])
name : botoo
url ://www.zalou.cn
page :88
isNonProfit :true
address : china
The usage of str.ljust() is like this;
s ="adc"
s.ljust(20,"+")'adc+++++++++++++++++'
s.rjust(20)'adc'
s.center(20,"+")'++++++++adc+++++++++'
Knowledge point expansion:
Alignment of strings in python
ljust(), rjust() and center() functions represent left, right, and center alignment, respectively
str.ljust(width[, fillchar]): left justify, width — specify the length of the string, fillchar — fill character, the default is a space;
str.rjust(width[, fillchar]): right justify, width — specify the length of the string, fillchar — fill character, the default is a space;
str.center(width[, fillchar]): center alignment, width — the total width of the string, fillchar — the filling character, the default is a space.
test ='hello world'print(test.ljust(20))print(test.ljust(20,'*'))print(test.rjust(20,'*'))print(test.center(20,'*'))print(test.center(20))
# The output results are as follows:
hello world******************hello world
****hello world*****
hello world
So far, this article on the example method of python right alignment is introduced. For more related content on how to right alignment in python, please search for ZaLou.Cn's previous articles or continue to browse the related articles below. I hope you will support ZaLou more in the future. Cn!
Recommended Posts