Best Practice to Pad Python String up to Specific Length – Python Tutorial

By | July 8, 2019

Padding a python string up to a fixed length is a very useful programming tip, which often can simplify the processing of strings in python. In this tutorial, we will introduce how to pad python string.

string processing in python

Preliminaries

  1. #create a string
  2. text = 'this is a test'
  3. #set the string lenth you want
  4. padding_len = 30
#create a string
text = 'this is a test'
#set the string lenth you want
padding_len = 30

There are three kinds of padding style:

String in right

  1. >>> str_right = format(text,'>'+str(padding_len))
>>> str_right = format(text,'>'+str(padding_len))

The output is:

  1. ' this is a test'
'                this is a test'

String in left

  1. >>> str_left = format(text,'<'+str(padding_len))
  2. >>> str_left
>>> str_left = format(text,'<'+str(padding_len))
>>> str_left

The output is:

  1. 'this is a test '
'this is a test                '

String in center

  1. >>> str_center = format(text,'^'+str(padding_len))
  2. >>> str_center
>>> str_center = format(text,'^'+str(padding_len))
>>> str_center

The output is:

  1. ' this is a test '
'        this is a test        '

You can find from the output, string is padded by blank char, if you want to use other char, you can refer this example.

  1. >>> str_center = format(text,'#^'+str(padding_len))
  2. >>> str_center
>>> str_center = format(text,'#^'+str(padding_len))
>>> str_center

The output is:

  1. '########this is a test########'
'########this is a test########'

Leave a Reply