Padding a string with leading specific characters in Python
Hey fellow Python coder! Today, in this tutorial, we will learn how to pad a string with specific characters in Python. Padding refers to adding additional characters either at the end or beginning of the string. In this tutorial, we will be adding leading characters to a Python string.
Method 1: Padding using String Concatenation
One of the most basic methods to implement padding is by using the power of string concatenation. For this approach, we will be using three variables: One is the original string, second is the character that we need to add as padding and last is the total length that we are targetting.
Also Read: Concatenate strings with space in Python
Then we perform the concatenation, but please note that since we are targetting a total length and hence we will only be adding the required amount of additional padding characters. Have a look at the code below:
sampleString = "codespeedy" leadingChar = "#" totalLength = 15 newString = leadingChar*(totalLength - len(sampleString)) + sampleString print("Original String : ", sampleString ) print("Padded String : ", newString)
When executed, the code results in the following output:
Original String : codespeedy Padded String : #####codespeedy
As you can see, the total target length was 15 and as a result, only 5 additional padding characters were added.
Method 2: Pad a string using str.rjust()
function
The same result can be achieved using the str.rjust()
function as displayed in the code snippet below. In this approach rather than manually computing the amount of characters that need to be added, we will pass the required value of variables to a function. The function will do all the computations itself and provide us with the result.
sampleString = "codespeedy" leadingChar = "#" totalLength = 15 newString = sampleString.rjust(totalLength, leadingChar) print("Original String : ", sampleString ) print("Padded String : ", newString)
Now if you execute this code, we will get the following result:
Original String : codespeedy Padded String : #####codespeedy
As you can see, we got the same result and we didn’t have to compute anything manually.
Also Read:
Happy Learning!
Leave a Reply