[英]How do I space pad my console output in Python?
如何在我剛剛在 python 中添加的兩行之間放置空格,以使其第二列對齊,而不管響應中有多少個字母?
代碼:
print(f'{email_address}')
print(f'{phone_number}')
print()
print(f'Hair: {hair.capitalize()} Eye color: {eye_color.capitalize()}')
print(f'Month: {month.capitalize()} Training: {training.capitalize()}')
print('--------------------------------------------------')
我希望頭發和眼睛顏色在同一行,月份和訓練部分也在同一行。 無論用戶輸入多少字,我也希望它們對齊。我希望我說得通
這就是我希望最后兩行的樣子:
Hair: Black Eye color: Brown
Month: April Training: Yes
您可以使用str.ljust()
方法:
hair = 'Black'
eye_color = 'Brown'
month = 'April'
training = 'Yes'
print(f'Hair: {hair.capitalize()}'.ljust(15), f'Eye color: {eye_color.capitalize()}')
print(f'Month: {month.capitalize()}'.ljust(15), f'Training: {training.capitalize()}')
Output:
Hair: Black Eye color: Brown
Month: April Training: Yes
括號中的15
告訴 python 使字符串長度至少為15
字符,如果字符串短於 15 個字符,則在字符串末尾添加空格,直到它達到 15 個字符。
如果字符串的開頭長度超過或等於 15 個字符,則字符串將保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.