Python | Padding a string upto fixed length
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()
# Python code to demonstrate # pad spaces in string # upto fixed length # initialising string ini_string = "123abcjw"padding_size = 15 # printing string and its length print ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in string res = ini_string.ljust(padding_size) # printing string and its length print ("final string : ", res, len(res)) |
chevron_right
filter_none
Output:
initial string : 123abcjw 8 final string : 123abcjw 15
Method #2: Using format
# Python code to demonstrate # pad spaces in string # upto fixed length # initialising string ini_string = "123abcjw" # printing string and its length print ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in string res = "{:<15}".format(ini_string) # printing string and its length print ("final string : ", res, len(res)) |
chevron_right
filter_none
Output:
initial string : 123abcjw 8 final string : 123abcjw 15
Method #3: Using operators( * and +)
# Python code to demonstrate # pad spaces in string # upto fixed length # initialising string ini_string = "123abcjw"padding_size = 15 # printing string and its length print ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in string res = ini_string + " "*(padding_size - len(ini_string)) # printing string and its length print ("final string : ", res, len(res)) |
chevron_right
filter_none
Output:
initial string : 123abcjw 8 final string : 123abcjw 15
Recommended Posts:
- Python string length | len()
- Python | Generate random string of given length
- Find length of a string in python (4 ways)
- Python | Optional padding in list elements
- Python program to print even length words in a string
- Python | Increase list size by padding each element by N
- Python | Reverse an array upto a given position
- Python | Find fibonacci series upto n using lambda
- Types of padding in convolution layer
- Find the length of each string element in the Numpy array
- Modify Numpy array to store an arbitrary length string
- Run Length Encoding in Python
- Python | Strings length summation
- SymPy | Permutation.length() in Python
- Python | Custom length Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



