Beginner

Python3 includes data type string. Strings in python are surrounded by single or double quotations. For example, ‘string’ and “string” are the same. String formatting is an important concept in python programming.

Padding in strings means to add spaces or characters on either side of the string. Padding is limited to the specified length. It can be padded to the left, right, or center and it can also be referred to as the string is right-aligned, left-aligned, or center aligned

In this article, we will learn how to format strings with padding in python3. We will see the different string methods and it’s limitations. If it is possible to align the text according to specified characters. 

Format Methods in Python

% Format

Strings have a built-in modulus operator “%” whose purpose is to perform string formatting. Formatting using the “%” operator has been there since the start but this method is not recommended after the introduction of format() method in Python 2.6 which we learn further on.

First, let’s take a look at how “%” formatting works. The syntax of using % modulus is:

"This is the string I want to format using %type_of_format and %type2_of_format" % (variable_name,variable_name2)

Let’s now try to understand the syntax, first comes the string which can be in either single quotation or double quotation. Inside the string literal, we need to write % and then it’s datatype which can be %s,%d, and many more. The string is then followed by a %operator and tuple with the values that you want to use.

A simple example to understand the % formatting method is:

print("%s%d is a great programming language!" %("Python",3))

Output:

Padding using % format

Now that we have a better idea of how % formatting works how could we add padding to our text using % operator. The simplest way of adding padding is to specify how many characters we want the string variable to take.

print('%15s' % ('Python',))

Output:

As we can see in the output the value has been padded to a specific length which is 15. To understand padding better look at the format below and assume steric represents space.

*********PYTHON

Let’s now take a look at padding the string right with spaces

print('%-15sa' % ('Python',))

Output:

If you notice in the code I have added a to show where right padding has ended. To understand right padding look at the format below and assume steric represents space.

Python*********a

Limitations

The % format only allows padding through spaces, only right and left padding is allowed. You can not align the text at the center of the specified characters using this method. The other disadvantage is that it decreases the readability of code because when several parameters are used code gets messy.

string.format() method

The newer and much better way of formatting strings was introduced after Python 2.6 and has been improved and is compatible with all Python 3.x versions. To understand the format method of strings let’s look into its syntax:

"This is the string I want to format using {} and {}".format(variable_name,variable_name2)

The format method formats the values in the placeholder which is defined using curly brackets { }. Values that are the variable name, as shown above, can be of any datatype and can also be in the form key=value list. Let’s see a simple example to understand the format method :

print("I love coding in Python {}. The version I'm using is {}".format("Python",3.6))

Output:

Padding with str.format()

format() method is powerful and has better readability. It overcame the limitations that were found in the string formatting using the % operator. One of the core differences between these two formatting techniques is that by default format method does left padding while % format does right padding. The number of lines we want to pad can be specified through the colon than the number you want.

print('{:15}a'.format('Python'))

Output:

The ‘a’ at the end of the output shows where the padding ends.

Now that we have understood how to add right padding in a string. Let’s take a look at how to add left padding using the python’s format method. The syntax within the placeholder is slightly different; it requires a greater than sign after the colon.

print('{:>15}'.format('Python'))

Output:

str.format() supports padding that can make the string characters center-aligned but depending on the number of characters in the string the split can be uneven. To center-align the text using the format method you need to add the “^” symbol inside the placeholder after the colon.

print('{:^11}'.format('Python')) #Padding is not even
print('{:^10}'.format('Py')) #Padding is even

Output

It is not clear through the output whether the padding is evenly spread or not. Another edge of using the “.format” method to format the string is that we can choose a character other than space to use for padding. You just need to add the character after the colon.

print('{:v^11}'.format('Python'))
print('{:v^10}'.format('Py'))

Output:

Padding Numbers

First let’s see how we can pad numbers using the % operator for integers, floating values, and signed numbers. As shown below for integers it is the same as string while for floating-point values you can add the required character you want and specify the decimal points. When looking at signed numbers, space needs to be added for minus signs.

#integer
print('%6d' % (12,))
#floating value
print('%07.3f' % (5.52324566322,))
#positive value
print('%+d' % (12,))
#negative value
print('% d' % (-12,))

Output:

Now let’s see how these operations can be performed with format() method. In format method it is forbidden to add a character before integer value as it doesn’t make sense. The plus point is that you can position the sign as you want.

#integer
print('{:6d}'.format(12))
#floating value
print('{:07.3f}'.format(5.52324566322))
#positive value
print('{:+d}'.format(12))
#negative value
print('{: d}'.format(-12))
#Positioning the sign
print('{:=5d}'.format((- 12)))

Output:

Other Python String Methods for Padding

Python also has inbuilt methods to perform string manipulation that includes padding. We’ll take a look at them one by one in this article.

Right Justify Python Text with rjust() method

rjust() method returns a right-justified string according to it’s length. Padding is done according to the parameter that is passed to the function. The syntax for rjust method is:

str.rjust(width[, fillchar]) #default fillchar is space

Let’s look at an example for rjust() method to understand further.

#using default fillchar
print("test".rjust(15))
#specifying character
print("test".rjust(15,'_'))

Output:

Left Justify Python Text with ljust() method

ljust() method returns a left-justified string according to it’s length. Padding is done according to the parameter that is passed to the function. The syntax for ljust method is:

str.ljust(width[, fillchar]) #default fillchar is space

Let’s look at an example for ljust() method to understand further:

#using default fillchar
print("test".ljust(15))
#specifying character
print("test".ljust(15,'0'))

Output:

Center Python Text with center() method

center() method returns a formatted string that is center aligned. Padding is done according to the parameter that is passed to the function. The syntax for center method is:

str.center(width[, fillchar]) #default fillchar is space

Let’s look at an example for center() method to understand further:

#using default fillchar
print("test".center(15))
#specifying character
print("test".center(14,'%'))

Output:

zfill() method

zfill method returns a formatted string with zeros padded on the left side of the text. You can not specify any other character in this method. The syntax for zfill method is:

str.zfill(width)

Let’s look at an example for zfill() method to understand further:

#using default fillchar
print("test".zfill(15))

Output:

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden