Topic Overview and Actualization

Hello, Code Explorer! Today, we're mastering the splitting and joining of strings in Python — vital string operations for efficient text analysis. Let's dive in!

Understanding String Splitting

Splitting breaks a string into substrings. Python simplifies this task using the split() method.

For example, let's split a sentence into words:

sentence = "Welcome to Python programming."
words = sentence.split()
print(words) # prints: ['Welcome', 'to', 'Python', 'programming.']

The split() method divides the string at spaces. However, we can specify a different delimiter. Here's an instance of splitting a list of comma-separated words:

fruit_list = 'apple,banana,cherry'
fruits = fruit_list.split(",")
print(fruits) # prints: ['apple', 'banana', 'cherry']

On top of that, you can provide a second parameter to split() that will configure the number of splits to do. Here is how it works:

fruit_list = 'apple,banana,cherry'
fruits = fruit_list.split(",", 1) # doing 1 split from the left, i.e., there will be 2 parts
print(fruits) # prints: ['apple', 'banana, cherry']
String Splitting: Dereference

Another useful feature when using split() on your string is dereference. Imagine you need to split a string containing the first and the last name joined by a comma (,), and you know there will always be at least two parts after the split. In such case you can retrieve the first and the last name by dereferencing the list:

string_to_split = "John,Doe"
first_name, last_name = string_to_split.split(",") # splitting and dereferencing
print(first_name) # prints: "John"
print(last_name)  # prints: "Doe"

However, in case there will be not enough elements in the list after splitting the string, an error will be thrown:

string_to_split = "John" # Just the first name, no last name
first_name, last_name = string_to_split.split(",")
# Raises "ValueError: not enough values to unpack (expected 2, got 1)"
Working with Python's String Splitting Methods

In addition to split(), Python provides other methods like splitlines() and rsplit() for specialized splitting.

The splitlines() method breaks a newline-separated text into lines:

text = "hello\nworld"
lines = text.splitlines()
print(lines) # prints: ['hello', 'world']

On the other hand, rsplit() does the opposite of split(). It splits the string from the right:

sentence = "hello, my world, I love python"
words1 = sentence.split(", ", 1)
words2 = sentence.rsplit(", ", 1)

print("Split: ", words1)  # prints: Split:  ['hello', 'my world, I love python'].
print("Rsplit: ", words2) # prints: Rsplit: ['hello, my world', 'I love python'].
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal