Python - Custom space size padding in Strings List

Python - Custom space size padding in Strings List

When working with lists of strings, there may be a need to adjust the strings so they align properly, especially if you want to display them in a tabular format. Padding strings with spaces (or other characters) is a common approach to this.

In Python, the built-in string methods ljust, rjust, and center are handy for this purpose. Let's delve into how to use these methods for custom space size padding in a list of strings.

1. Using ljust:

ljust is used to left-align a string by padding it with a specified character (default is space) to achieve a given width.

strings = ["apple", "banana", "cherry"] padded_strings = [s.ljust(10) for s in strings] for s in padded_strings: print(s, end='|') 

Output:

apple |banana |cherry | 

2. Using rjust:

rjust does the opposite of ljust, padding to the left of the string to right-align it.

padded_strings = [s.rjust(10) for s in strings] for s in padded_strings: print(s, end='|') 

Output:

 apple| banana| cherry| 

3. Using center:

center centers the string within the given width.

padded_strings = [s.center(10) for s in strings] for s in padded_strings: print(s, end='|') 

Output:

 apple | banana | cherry | 

4. Custom Padding Size:

To pad based on a custom size derived from the strings list (for instance, based on the length of the longest string), you can do the following:

max_length = max(len(s) for s in strings) padded_strings = [s.ljust(max_length + 5) for s in strings] for s in padded_strings: print(s, end='|') 

Output:

apple |banana |cherry | 

In the above code, we first compute the max_length, which is the length of the longest string in the list. We then use ljust to pad each string to the width of max_length + 5.

5. Custom Padding Character:

All these methods also support padding with a character other than space. For instance:

padded_strings = [s.center(10, '*') for s in strings] for s in padded_strings: print(s, end='|') 

Output:

**apple***|**banana**|**cherry**| 

Conclusion:

By combining Python's built-in string padding methods with list comprehensions, you can easily adjust the strings in a list to have custom padding, alignment, and width. This can be particularly useful for tasks like aligning output in tabular form.


More Tags

customvalidator wcf javax ios-app-extension angular2-http innodb ls mule-component symfony-1.4 markers

More Programming Guides

Other Guides

More Programming Examples