Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 252
Jeff Avatar asked Aug 23 '11 15:08

Jeff


People also ask

How do I format a string to a specific length in Python?

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.

How do you format a variable in a string in Python?

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.

Can you use .format on variables Python?

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.

How do I fix the length of a string in Python?

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.


2 Answers

You could use .join():

nums = (1, 2, 3)
"\t".join(str(x) for x in nums) # Joins each num together with a tab.
like image 106
Chris Pickett Avatar answered Oct 16 '22 03:10

Chris Pickett


Using ''.format

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

producing

>>>  1  2  3
like image 32
PapaKuma Avatar answered Oct 16 '22 04:10

PapaKuma