In Python, with strings, you can use center and join methods for different purposes. Here are the best examples and the differences.

Table of contents

  1. Center method
  2. Join method
  3. Conclusion
Python Center Vs Join methods
Photo by Karolina Grabowska on Pexels.com

Center method

The center method is used to center-align a string within a specified width. It takes two arguments: the width of the resulting string, and an optional character to fill the empty space (default is a space). The original string is placed in the center, and the remaining space on both sides is filled with the specified character.

original_string = "Python"
centered_string = original_string.center(10, '*')
print(centered_string)

Output

**Python**



** Process exited - Return Code: 0 **
Press Enter to exit terminal

Join method

To concatenate a list of strings into a single string, you can use the join method using a specified delimiter. It is a string method that takes an iterable (e.g., a list or tuple) of strings as its argument. The method joins these strings with a delimiter.

words = ["Hello", "World", "Python"]
joined_string = " ".join(words)
print(joined_string)

Output:

Hello World Python

Conclusion

  • Use the center method to align a string within a specified width.
  • Use join to concatenate a list of strings into a single string, with a specified delimiter between them.
  • Remember that these methods do not modify the original strings; they return new strings with the desired modifications.