Register Login

Padding Strings in Python

Updated Sep 21, 2022

Padding strings in Python is one of the most standard and common practices for Python users. There are certain functions in Python that helps in string padding. These are

  1. .ljust()
  2. .rjust()
  3. .center()
  4. .zfill()
  5. .format() functions
  6. f-strings

This article will provide a detailed idea about Python String Padding and its uses for programmers.

What does String Padding mean?

String padding generally means adding non-informative characters within a string either to one or both ends of the string input.

Use of String Padding:

A typical use case for padding strings is outputting tables, such as to display information in a tabular format. Users often do this for output formatting and alignment purposes.

But it can have more valid practical applications. Users can do this in various methods, including using Pandas (Python Library) to convert their data to an exact tabular format. This way, the Python interpreter will handle the output formatting itself.

Types of Padding Strings in Python:

Let us grab some ideas about the types of String Padding in Python before taking a closer look at the Python functions mentioned above.

Left Padding:

When users add left padding to a string implies adding a character input at the start of the Python string to make it of a specified length. It means when users insert a character to the end of a String input to create a new Python string of a specified length; it is called Left Padding.

Left padding is reasonable for creating file names that mostly start with numeric characters; that generate in sequence.

One of the most common practices of using left padding is:

To avoid situations like sorting several files in the following order: 1, 3, 11, 5, 6, 12, and so on. It happens when users add the number at the beginning of the file, and the operating system sorts these files in the above order.

It occurs, of course, because of the rules of lexicographical sorting. All a user has to do is add left padding to the numbers with the appropriate number of zeroes, which keeps their original value intact.

Center Padding:

When users use the center padding, the Python inserts the given character at both the ends of the strings. It will have an equal number of widths until the newly formed Python string is of a typical string length.

It implies that the Python interpreter will add the character input equally to both sides of the input string; until the new string resembles the given length. It centers on the string input of a specified or given length.

Right Padding:

Similar to the left padding, the right padding also aligns a character input in equal measure to both sides of the string; until the new string resembles the inserted length.

Function in Python for String Padding:

There are seven techniques for padding string in Python. These are as follows:

.ljust():

The ljust() function aligns to the left side by adding padding to the right end of the string input.

Syntax:

string.ljust(width, char)

The ljust() function takes two parameters: width and fillchar. These are:

Width:

It specifies the length of the string after the padding is complete. It is compulsory.

Fillchar:

This parameter represents the character users want to pad to the original string. It is optional.

Code Snippet:

Student1 = ['Rahul', 'Roll no. 1', 'Marks: 40']
Student2 = ['Ali', 'Roll no. 2', '2 mg']
Student3 = ['Akash', 'Roll no. 3', 'Marks: 40']
for students in [Student1, Student2, Student3]:
for entry in students:
print(entry.ljust(50), end ='')
print()

Output:

.rjust():

This function is similar to the ljust() function. rjust() aligns the string to the right by adding padding to the left (beginning) of the Python string.

Syntax:

string.rjust(width, char)

The ljust() function takes two parameters: width and fillchar. These are:

Width:

It specifies the length of the string after the padding is complete. It is compulsory.

Fillchar:

This parameter represents the character users want to pad to the original string. It is optional.

Code Snippet:

list_of_original_names = []
list_of_padded_names = []
for x in range(1, 15):
    list_of_original_names.append(str(x) + ".name")
    list_of_padded_names.append(str(x).rjust(3, '0') + ".name")
print("Lexicographical sorting without padding:")
print(sorted(list_of_original_names))
print()
print("Lexicographical sorting with padding:")
print(sorted(list_of_padded_names))

Output:

.center():

Using the center() function, users can efficiently align the string input to the center with the provided width as the parameter.

Syntax:

string.center(width)

This function has only one parameter, width, which adds blank spaces to both ends of the string input.

Code Snippet:

example_of_strings = ["When users use this", "center() function", "it aligns the string to the center", "by adding white spaces", "on both sides"]
for s in example_of_strings:
    print(s.center(100, ' '))

Output:

.zfill():

The working of the zfill() function is similar to that of the rjust() function. It has a zero as a specified character. The function left pads the string input with zeroes until the string resembles the provided length.

One significant difference between the two functions is that in the case of zfill() if the string starts with any sign plus or minus (+ or -), it will return the padding with that sign.

Code Snippet:

neutral = '1'
positive = '+1'
negative = '-1'
length = 3
print(neutral.zfill(length))
print(positive.zfill(length+1))
print(negative.zfill(length+2))

Output:

str.format():

This function is the most advanced for padding strings in Python. Users can use this function for padding to the left, right, or center. It also provided other formatting properties apart from the above-sited padding formats.

Syntax:

string.format(value_1, value_2, value_3, value_4… value_n)

It has parameters that specify the keys to be formatted. It returns the string after formatting the specified keys and setting them within the string placeholders, which the user will define by {}.

Code Snippet:

if __name__ == '__main__':
    demo = 'Hello'
    pad = '0'
    len = 20
    a = ('{:' + pad + '<' + str(len) + '}').format(demo) # x = '{:X>8}'.format(s)
    print(a) 

Output:

Another Example of .format() is as follows:

print("We can add Placeholders as given by {00}, or with a {value}".format("a number", value ="value having a name."))
print("Also, we can add placeholders, written {}, without adding a {} or {}".format("implicitly", "name", "number"))

Output:

Using f-string:

Another method to pad strings in Python is to use the f-string.

Syntax:

f{value}

Code Snippet:

if __name__ == '__main__':
    demo = 'Hello'
    pad = '0'
    len = 20
    a = f'{demo:{pad}>{len}}' # x = '{:X>8}'.format(s)
    print(a)  

Output:

format():

Finally, we can use this built-in function of Python for string padding. It can add padding to both strings and numbers.

format (value)

Code Snippet:

if __name__ == '__main__':
    demo = 'Hello'
    pad = '0'
    len = 20
    a = format(demo, pad + '>' + str(len)) # x = '{:X>8}'.format(s)
    print(a)  

Output:

Conclusion:

In Python, padding a string is somewhat a straightforward mechanism. This article has given all possible methods for string padding.

Programmers can use any of the above functions for padding a string efficiently. It will noticeably improve the performance and readability of the output. Specifically, if the data is in tabular format, a user can easily read it.


×