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 '
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3