[python] 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.

This question is related to python string format

The answer is


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

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


You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.

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

The result is 69*****

And for the left:

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

The result will be ###69

Also to add zeros you can simply use:

numstr.zfill(8)

Which gives you 69000000 as the result.


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 += " "

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:

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    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=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)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

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.


name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters

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'

Centered

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

For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax


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]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?