How do I make a fixed size formatted string in python?

PythonPython 2.7

Python Problem Overview


I want to create a formatted string with fixed size with fixed position between fields. An example explains better, here there are clearly 3 distinct fields and the string is a fixed size:

XXX        123   98.00
YYYYY        3    1.00
ZZ          42  123.34

How can I apply such formatting to a string in python (2.7)?

Python Solutions


Solution 1 - Python

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

> 10s format a string with 10 spaces, left justified by default > > 3d format an integer reserving 3 spaces, right justified by default > > 7.2f format a float, reserving 7 spaces, 2 after the decimal point, > right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanioView Question on Stackoverflow
Solution 1 - PythonLevonView Answer on Stackoverflow