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.
Preliminaries
#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
>>> str_right = format(text,'>'+str(padding_len))
The output is:
' this is a test'
String in left
>>> str_left = format(text,'<'+str(padding_len)) >>> str_left
The output is:
'this is a test '
String in center
>>> str_center = format(text,'^'+str(padding_len)) >>> str_center
The output is:
' 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.
>>> str_center = format(text,'#^'+str(padding_len)) >>> str_center
The output is:
'########this is a test########'