Python string format for tuple variables

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

>>>print '%3d' % nums 

which will produce

 >>> 1 2 3 

Hope this is not a duplicate question, but I cannot find it if that is the case. Thanks

+7
source share
6 answers

Try the following:

 print ('%3d'*len(nums)) % tuple(nums) 
+7
source

Since no one has said this yet:

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

You can use .join ():

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

Is that enough for you?

 print ' '.join(str(x) for x in nums) 
+1
source

Using '.format

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

production

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

All Articles