Home >Backend Development >Python Tutorial >How to right align in python
For example, there is a dictionary as follows:
>>> dic = { "name": "botoo", "url": "http://www.123.com", "page": "88", "isNonProfit": "true", "address": "china", }
The desired output result is as follows:
Related Recommended: "Python Video Tutorial"
First get the maximum value of the dictionary max(map(len, dic.keys()))
Then use
Str.rjust() Right alignment
or
Str.ljust() Left alignment
or
Str.center() Centering method Sequential output.
>>> dic = { "name": "botoo", "url": "http://www.123.com", "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 : http://www.123.com page : 88 isNonProfit : true address : china >>> for k in dic: print(k.rjust(d),":",dic[k]) name : botoo url : http://www.123.com page : 88 isNonProfit : true address : china >>> for k in dic: print(k.center(d),":",dic[k]) name : botoo url : http://www.123.com page : 88 isNonProfit : true address : china >>>
There is also this about the usage of str.ljust();
>>> s = "adc" >>> s.ljust(20,"+") 'adc+++++++++++++++++' >>> s.rjust(20) ' adc' >>> s.center(20,"+") '++++++++adc+++++++++' >>>
The above is the detailed content of How to right align in python. For more information, please follow other related articles on the PHP Chinese website!