sam*_*moz 35 python string formatting text
我有一些数据,我以3列格式显示,形式如下:
key: value key: <tab> key: value <tab> key: value
.
这是一个例子:
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
Run Code Online (Sandbox Code Playgroud)
但是,我想如果这些数字完全一致,例如:
a: 1
b: 12
c: 123
Run Code Online (Sandbox Code Playgroud)
我怎么能用Python做到这一点?
这是我现有的打印代码:
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]))
Run Code Online (Sandbox Code Playgroud)
Col*_*ant 76
在python 2.6+(它是3中的标准方法)中,字符串格式化的"首选"方法是使用string.format()(可在此处找到完整的文档).正当理由可以用
"a string {0:>5}".format(foo)
Run Code Online (Sandbox Code Playgroud)
但是,这将使用5个位置
"a string {0:>{1}}".format(foo, width)
Run Code Online (Sandbox Code Playgroud)
也是有效的,并将使用传递给.format()的值宽度.
Chr*_*heD 34
在Python 2.5中使用rjust(在字符串上).另外,尝试习惯python中的字符串格式,而不是仅仅连接字符串.下面的rjust和字符串格式的简单示例:
width = 10
str_number = str(ord('a'))
print 'a%s' % (str_number.rjust(width))
Run Code Online (Sandbox Code Playgroud)
Nad*_*mli 26
使用python字符串格式:'%widths'
其中width是一个整数
>>> '%10s' % 10
' 10'
>>> '%10s' % 100000
' 100000'
Run Code Online (Sandbox Code Playgroud)
在Python 3.6中,可以使用Literal String Interpolation,它不那么冗长,使用起来可能更直观:
width = 5
number = 123
print (f'{number:>{width}}')
Run Code Online (Sandbox Code Playgroud)
要不就:
number = 123
print (f'{number:>5}')
Run Code Online (Sandbox Code Playgroud)
它重用了许多str.format()
语法。
我猜/希望这将是将来的首选方式。