Zone Of Makos

Menu icon

Split and Join in Python

Splitting and joining strings are two common operations in Python that you'll often use when working with text. The split() method is used to split a string into a list of substrings based on a specified delimiter, while the join() method is used to join a list of strings into a single string, with a specified delimiter separating each element. In this lesson, we'll explore how to use the split() and join() methods in Python and some common use cases for each method.

The split() Method

The split() method is used to split a string into a list of substrings based on a specified delimiter. By default, the delimiter is a whitespace character, but you can specify a custom delimiter using the optional separator argument. The split() method returns a list of the substrings.


my_string = "Hello World"
split_string = my_string.split()
print(split_string)  # Output: ["Hello", "World"]

my_string_with_separator = "Apple,Banana,Cherry"
split_string_with_separator = my_string_with_separator.split(",")
print(split_string_with_separator)  # Output: ["Apple", "Banana", "Cherry"]

The join() Method

The join() method is used to join a list of strings into a single string, with a specified delimiter separating each element. The join() method is called on the delimiter string and takes the list of strings to be joined as its argument. The join() method returns the joined string.


my_list = ["Apple", "Banana", "Cherry"]
delimiter = ","
joined_string = delimiter.join(my_list)
print(joined_string)  # Output: "Apple,Banana,Cherry"

Conclusion

Splitting and joining strings are two common operations in Python that you'll often use when working with text. The split() method is used to split a string into a list of substrings based on a specified delimiter, while the join() method is used to join a list of strings into a single string, with a specified delimiter separating each element. The split() and join() methods are very useful when working with text data in Python, and knowing how to use them effectively will save you time and make your code more efficient.