Padding A String in Python
In this tutorial, we are going to learn about how to do Padding a string to fixed-length in Python.
It can be done in 3 ways which are given below:
- Left Padding
- Right Padding
- Center Padding
Padding is similar to the alignment of the text.
Also, read: Count overlapping substrings in a given string in Python
ljust:-
This method does the padding to the left side (so the string is aligned to the left side). The padding is done using the default character(space).
ljust function contains two parameters width, fillchar. The width parameter sets the length of the string with padding according to a given input, The length also includes the length of the string(ex:- if width=20 and string is “hello” then the total output of string is 20, i.e string contains 15 spaces after hello). fillchar parameter is used to fill the padding space by replacing space(character).
Example:-
See the below code:
a = input("Enter a string: ") n = int(input("Enter the length:")) print('Before padding: ',a) print('Left Padding: ',a.ljust(n),'!')
Output:
Enter a string: hello Enter the length: 20 Before padding: hello Left Padding: hello !
After padding the total length of the Python string is 20.
Now we will print the string using fillchar argument.
a = input("Enter a string: ") n = int(input("Enter the length:")) print('Before padding: ',a) print('Left Padding: ',a.ljust(n,'$'))
Output:
Enter a string: hello Enter the length: 20 Before padding: hello Left Padding: hello$$$$$$$$$$$$$$$
rjust:-
rjust method does the padding to the right side (so the string is aligned to the right side). The padding is done using the default character(space). Here the spaces are contained before the string.
Example:-
a = input("Enter a string: ") n = int(input("Enter the length:")) print('Before padding: ',a) print('Right Padding: ',a.rjust(n,'$'))
Output:-
Enter a string: hello Enter the length: 20 Before padding: hello Right Padding: $$$$$$$$$$$$$$$hello
Center:-
Center method does the padding to the center (so the string is aligned to the center). The padding is done using the default character(space). Here string contains half of the spaces before the string and another half after the string.
Example:-
a = input("Enter a string: ") n = int(input("Enter the length:")) print('Before padding: ',a) print('Center Padding: ',a.center(n,'$'))
Output:
Enter a string: hello Enter the length: 21 Before padding: hello Center Padding: $$$$$$$$hello$$$$$$$$
Here output contains 8 ‘$’ symbols before the string and 8 ‘$’ symbols are after the string. Total 16 $ symbols are used because the length of the string is 5 (16+5=21).
Leave a Reply