Jeff
Jeff

Reputation: 7210

python string format for variable tuple lengths

I have a tuple of numbers let's say nums = (1, 2, 3). The length of nums is not constant. Is there a way of using string formatting in python to do something like this

>>>print '%3d' % nums

that will produce

>>>   1   2   3

Hope it's not a repeat question, but I can't find it if it is. Thanks

Upvotes: 9

Views: 5886

Answers (6)

PapaKuma
PapaKuma

Reputation: 21

Using ''.format

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

producing

>>>  1  2  3

Upvotes: 2

RightmireM
RightmireM

Reputation: 2492

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

Upvotes: -1

viraptor
viraptor

Reputation: 34145

Is this enough for you?

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

Upvotes: 1

nmichaels
nmichaels

Reputation: 50941

Since nobody's said it yet:

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

Upvotes: 4

Chris Pickett
Chris Pickett

Reputation: 2822

You could use .join():

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

Upvotes: 3

Gerrat
Gerrat

Reputation: 29690

Try this:

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

Upvotes: 7

Related Questions