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
In Python, strings have a built-in method named ljust . The method lets you pad a string with characters up to a certain length. The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.
In the above example, we create the variables to be formatted into the string. Then, in the simples form, we can use {} as placeholders for the variables to be used. We then apply the . format() method to the string and specify the variables as an ordered set of parameters.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length. The first parameter those methods is the total character number after transforming the string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With