如何右对齐数字数据? [英] How to right-align numeric data?

查看:22
本文介绍了如何右对齐数字数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据以 3 列格式显示,格式如下:

I have some data that I am displaying in 3 column format, of the form:

key: 值 key: 键:值 键:值.

这是一个例子:

p: 1    sl: 10  afy: 4
q: 12   lg: 10  kla: 3
r: 0    kl: 10  klw: 3
s: 67   vw: 9   jes: 3
t: 16   uw: 9   skw: 3
u: 47   ug: 9   mjl: 3
v: 37   mj: 8   lza: 3
w: 119  fv: 8   fxg: 3
x: 16   fl: 8   aew: 3

但是,我希望数字是否正确对齐,例如:

However, I'd like if the numbers were all right aligned, such as:

a:   1
b:  12
c: 123

如何在 Python 中执行此操作?

How can I do this in Python?

这是我现有的打印代码:

Here is the existing printing code I have:

print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "	" +
    str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "	" +
    str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))

推荐答案

在 Python 2.5 中使用 rjust(在字符串上).另外,尝试在 python 中习惯字符串格式,而不是仅仅连接字符串.下面是 rjust 和字符串格式的简单示例:

In Python 2.5 use rjust (on strings). Also, try to get used to string formatting in python instead of just concatenating strings. Simple example for rjust and string formatting below:

width = 10
str_number = str(ord('a'))
print 'a%s' % (str_number.rjust(width))

这篇关于如何右对齐数字数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆