Home > Article > Backend Development > How Can I Align Strings in Python for Aesthetic Output?
Aligner: Aligning Strings for Aesthetic Output
When printing multiple strings with varying lengths, formatting issues may arise, causing an unaligned appearance. This article introduces two elegant methods, str.format and Python 3's f-strings, to overcome this obstacle and achieve organized output.
Method 1: str.format
str.format allows for flexible alignment of strings using placeholder values. The syntax is {index: alignment <|> width}, where:
For example, the following code prints strings of varying lengths left and right-aligned with a minimum width of 5:
'{0: <5}'.format('s') # 's ' '{0: >5}'.format('ss') # ' ss'
Method 2: Python 3 F-Strings
In Python 3, f-strings provide a convenient way to align strings using the same syntax as str.format. However, no argument's index is specified, and a = symbol is used instead of the colon:
f'{s:>5}' # ' ss' f'{s:<5}' # 's '
The above is the detailed content of How Can I Align Strings in Python for Aesthetic Output?. For more information, please follow other related articles on the PHP Chinese website!