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. Th开发者_如何学编程anks
Try this:
print ('%3d'*len(nums)) % tuple(nums)
Since nobody's said it yet:
''.join('%3d' % num for num in nums)
You could use .join():
nums = (1, 2, 3)
"\t".join(str(x) for x in nums) # Joins each num together with a tab.
Using ''.format
nums = (1, 2, 3)
print(''.join('{:3d} '.format(x) for x in nums))
producing
>>> 1 2 3
Is this enough for you?
print ' '.join(str(x) for x in nums)
params = '%d'
for i in range(1,15):
try:
newnum = (params)%nums
except:
params = params + ',%d'
next
print newnum
精彩评论