Python | Padding a string upto fixed length
Last Updated :
23 Mar, 2023
Given a string, the task is to pad string up to given specific length with whitespaces. Let’s discuss few methods to solve the given task.
Method #1: Using ljust()
Python3
ini_string = " 123abcjw "
padding_size = 15
print ("initial string : ", ini_string, len (ini_string))
res = ini_string.ljust(padding_size)
print ("final string : ", res, len (res))
|
Output:
initial string : 123abcjw 8
final string : 123abcjw 15
Method #2: Using format
Python3
ini_string = " 123abcjw "
print ("initial string : ", ini_string, len (ini_string))
res = "{:< 15 }". format (ini_string)
print ("final string : ", res, len (res))
|
Output:
initial string : 123abcjw 8
final string : 123abcjw 15
Method #3: Using operators( * and +)
Python3
ini_string = " 123abcjw "
padding_size = 15
print ("initial string : ", ini_string, len (ini_string))
res = ini_string + " " * (padding_size - len (ini_string))
print ("final string : ", res, len (res))
|
Output:
initial string : 123abcjw 8
final string : 123abcjw 15
Method#4: Using f-strings
Algorithm:
- Initialize a string ‘ini_string‘ with a value.
- Calculate the length of ‘ini_string’ using the ‘len()’ function.
- Print the initial string and its length using the ‘print()’ function and f-strings.
- Use the ‘f-string’ with format specifier ‘{:<N}’ to left justify the ‘ini_string’ and pad it with spaces on the right side upto ‘padding_size’ length.
- Store the resulting string in a new variable ‘res’.
- Print the final string and its length using the ‘print()’ function and f-strings.
Python3
ini_string = "123abcjw:, .@! eiw"
ini_string = "123abcjw"
padding_size = 15
print (f "initial string : {ini_string} {len(ini_string)}" )
res = f "{ini_string:<{padding_size}}"
print (f "final string : {res} {len(res)}" )
|
Output
initial string : 123abcjw 8
final string : 123abcjw 15
Time Complexity: The time complexity of the algorithm is O(1) as it does not depend on the length of the input string. The ‘len()’ function, f-string formatting, and string concatenation all have constant time complexity.
Space Complexity: The space complexity of the algorithm is O(1) as it only uses a fixed amount of memory to store the input string, padding size, and resulting string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...