2017-03-02 37 views
0

我正在尝试将某些文本与变量对齐对齐。使用变量对齐格式?

比如这个作品:

>>> print '{:>10}'.format('foo') 
     foo 

但这并不:

>>> x = 10 
>>> print '{:>x}'.format('foo') 
+0

您可以使用print('{:>'+ str(x)+'}').format('foo')',虽然看起来真的很丑。 –

回答

4

检查docs

您正在寻找:

>>> print '{0:>{x}}'.format('foo', x=x) 
     foo 
+0

rjust()对于那个 – Drako

+0

这种格式更好的是它可以与新的f-字符串一起使用。 –

0

Python有rjust ()ret瓮文本右对齐 另外你提供它的参数:宽度,fillchar;例如:

a = 10 
print str(a).rjust(20)