且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用Python中的空格填充一个固定长度的字符串?

更新时间:2023-11-15 16:30:46

$ 格式

b
$ b
 >>> a =John
>>>格式(a)
'John'


I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.

Problem: I need to put a string in a certain length "field".

For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.

I need this to work for any string put in for the variable "name".

I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.

This is super simple with format:

>>> a = "John"
>>> "{:<15}".format(a)
'John           '