9

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

6 Answers 6

7

Try this:

print ('%3d'*len(nums)) % tuple(nums)
Sign up to request clarification or add additional context in comments.

Comments

4

Since nobody's said it yet:

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

Comments

3

You could use .join():

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

Comments

2

Using ''.format

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

producing

>>>  1  2  3

Comments

1

Is this enough for you?

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

Comments

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

2 Comments

Have you even tried to run this? Hint: it will crash if the size of nums is larger than 1.
When looking at it now, I see how you're thinking. However, there must be an indentation error on the last line. The way the code is written here, it will crash if len(nums) > 1, and if len(nums) == 1, it will print the number 14 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.