How to pad a string to a fixed length with spaces in Python?


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.

Asked By: user2977230



string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces

This will add the number of spaces needed, provided the field has length >= the length of the name provided

Answered By: Aswin Murugesh

First check to see if the string’s length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "
Answered By: Matt
name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters
Answered By: user2629998

You can use the ljust method on strings.

>>> name = 'John'
>>> name.ljust(15)
'John           '

Note that if the name is longer than 15 characters, ljust won’t truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]
Answered By: Ismail Badawi

This is super simple with format:

>>> a = "John"
>>> "{:<15}".format(a)
'John           '
Answered By: Games Brainiac

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str
Answered By: dragon40226

If you have python version 3.6 or higher you can use f strings

>>> string = "John"
>>> f"{string:<15}"
'John           '

Or if you’d like it to the left

>>> f"{string:>15}"
'          John'


>>> f"{string:^15}"
'     John      '

For more variations, feel free to check out the docs:

Answered By: Justin Furuness

I know this is a bit of an old question, but I’ve ended up making my own little class for it.

Might be useful to someone so I’ll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

2021-03-02 update: Improved a bit – when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don’t know what was previously written to the console and whether you want to retain it.

This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.

class consolePrinter():
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
overwriteLine = False
# -------------------------------------------------------------------------    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"

    prevOverwriteLine = consolePrinter.overwriteLine
    if prevOverwriteLine:
        #Previous line entry can be overwritten, so do so
        sys.stdout.write("r" + ctrlString.format(stringIn))
        #Previous line entry cannot be overwritten, take a new line
        sys.stdout.write("n" + stringIn)
    #Update the class variable for prevOverwriteLine
    consolePrinter.overwriteLine = overwriteThisLine


Which then is called via:

consolePrinter.writeline("text here", True) 

If you want this line to be overwriteable

consolePrinter.writeline("text here",False)

if you don’t.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

Answered By: Amiga500

You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.
The first parameter those methods is the total character number after transforming the string.

Right justified (add to the left)

numStr = '69' 
numStr = numStr.rjust(5, '*')

The result is ***69

Left justified (add to the right)

And for the left:

numStr = '69' 
numStr = numStr.ljust(3, '#')

The result will be 69#

Fill with Leading Zeros

Also to add zeros you can simply use:


Which gives you 00000069 as the result.

Answered By: Matin Ashtiani

I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:

>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'

Thought it was a touch more readable than the format version:

>>> f'{res[0]:>4}x{res[1]:>4}'
Answered By: Gringo Suave
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.