变量元组长度的python字符串格式

时间:2011-08-23 15:25:23

标签: python printing string-formatting

我有一个数字元组,让我们说nums =(1,2,3)。 nums的长度不是恒定的。有没有办法在python中使用字符串格式来做这样的事情

>>>print '%3d' % nums

将产生

>>>   1   2   3

希望这不是一个重复的问题,但如果是的话,我找不到它。 感谢

6 个答案:

答案 0 :(得分:7)

试试这个:

print ('%3d'*len(nums)) % tuple(nums)

答案 1 :(得分:4)

因为没有人说过:

''.join('%3d' % num for num in nums)

答案 2 :(得分:3)

你可以使用.join():

nums = (1, 2, 3)
"\t".join(str(x) for x in nums) # Joins each num together with a tab.

答案 3 :(得分:2)

使用'' .format

nums = (1, 2, 3)
print(''.join('{:3d} '.format(x) for x in nums))
制造

>>>  1  2  3

答案 4 :(得分:1)

这对你来说够了吗?

print ' '.join(str(x) for x in nums)

答案 5 :(得分:-1)

params = '%d'
for i in range(1,15):
    try:
        newnum = (params)%nums
    except:
        params = params + ',%d'
        next
    print newnum