Home > Article > Backend Development > How Can I Print Strings in Fixed Width Columns?
Printing Strings in Fixed Width Columns
The problem of unevenly aligned string output arises when printing strings of different lengths. To rectify this, consider utilizing string formatting techniques.
Using str.format() with Padding
'{0: <5}'.format('s') # Left-align with 5 characters '{0: >5}'.format('ss') # Right-align with 5 characters
The number '0' refers to the index of the argument passed to str.format(). The '<' or '>' specifies the alignment.
Using f-Strings with Padding
sub_str = 's' for i in range(1, 6): s = sub_str * i print(f'{s:>5}') # Right-align with 5 characters
f-strings offer a convenient way to format strings inline. The '>' or '<' symbol controls the alignment.
In these examples, single quotation marks were occasionally added to highlight the desired width of the printed strings. By leveraging these formatting techniques, one can ensure that strings are printed in neat, aligned columns.
The above is the detailed content of How Can I Print Strings in Fixed Width Columns?. For more information, please follow other related articles on the PHP Chinese website!