Probably, the most elegant way is to use the format
method. It allows to easily define the space a string will use:
>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> print '{0:17}: {1} {2} €'.format(name, asterisks, price)
Якета : **************************** 1250.23 €
Should you need to programmatically define padding size (for instance, to dynamically accept larger strings instead of hard-coding its size), simply use ljust
:
>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = 17
>>> print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
Якета : **************************** 1250.23 €
Considering the case when the maximum string size is unknown previously and the script must adapt to it, we only need to calculate the maximum string size and place it in padding
:
>>> names = ['abc', 'defghijklm', 'op', 'q']
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = max(map(len, strings))
>>> for name in names:
print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
abc : **************************** 1250.23 €
defghijklm: **************************** 1250.23 €
op : **************************** 1250.23 €
q : **************************** 1250.23 €
This thread has a pretty similar issue.