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

问题描述

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

键:value键:< tab>键:值<标签>键:值



下面是一个例子:
$ b

  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

然而,如果数字完全对齐,比如:
$ b

  a:1 
b:12
c:123

如何在Python中执行此操作?



是我现有的打印代码:

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


解决方案

在Python 2.5使用rjust(在字符串上)。此外,尝试习惯在Python中,而不是只是串联字符串。

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


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

key: value key: <tab> key: value <tab> key: value.

Here's an example:

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

How can I do this in Python?

Here is the existing printing code I have:

print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
    str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
    str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
解决方案

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))

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

07-08 04:00
查看更多