简体   繁体   English

如何在 Python 中填充我的控制台 output?

[英]How do I space pad my console output in Python?

How do I put spaces between two lines I just added in python, to make it so that the second columns align, regardless of how many letters are in the responses?如何在我刚刚在 python 中添加的两行之间放置空格,以使其第二列对齐,而不管响应中有多少个字母?

Code:代码:

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('--------------------------------------------------')

I want the hair and the eye_color to be in the same line, the month and the training part to be in the same line as well.我希望头发和眼睛颜色在同一行,月份和训练部分也在同一行。 I also want them to align regardless of the number of words the user type in. I hope I make sense无论用户输入多少字,我也希望它们对齐。我希望我说得通

This is how I want the last two lines to look like:这就是我希望最后两行的样子:

Hair: Black     Eye color: Brown
Month: April    Training: Yes

You can use the str.ljust() method:您可以使用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: Output:

Hair: Black     Eye color: Brown
Month: April    Training: Yes

Where the 15 in the brackets tells python to make the string at least 15 characters long, adding white-spaces to the end of the string if the string is shorter than 15 characters until is it 15 characters.括号中的15告诉 python 使字符串长度至少为15字符,如果字符串短于 15 个字符,则在字符串末尾添加空格,直到它达到 15 个字符。

If the string was over or equal to 15 characters long to begin with, then the string will remain unchanged.如果字符串的开头长度超过或等于 15 个字符,则字符串将保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM