Python List

Splitting and joining

Joining and splitting are commonly used operations for manipulating strings and lists.

1. Joining a list into a string:

Joining is the process of combining a list of strings into a single string. We use the .join() method, where the list elements are concatenated, and a specified delimiter is placed between them.

Example 1: joining with spaces

words = ['Hello', 'world', 'in', 'Python']
sentence = ' '.join(words)

print(sentence)  # Output: "Hello world in Python"

In this case, we have a list ['Hello', 'world', 'in', 'Python']. We use ' '.join() to combine the list elements into a string, and the delimiter between each word is a space (' ').

Example 2: joining with commas and space

fruits = ['apple', 'banana', 'cherry']
result = ', '.join(fruits) 

print(result)  # Output: "apple, banana, cherry"

Here, the list of fruits is joined into a single string with ","  (comma followed by space) as the delimiter.


2. Splitting a string into a list:

Splitting takes a string and breaks it into a list of substrings based on a specified delimiter. The .split() method is used for this.

Example 1: splitting by spaces (default behavior)

sentence = "Python is amazing"
words = sentence.split()

print(words)  # Output: ['Python', 'is', 'amazing']

In this example, we take a sentence and split it into a list of words by default using spaces as the delimiter.

Example 2:  splitting by commas

data = "apple,banana,cherry"
fruits = data.split(',')  

print(fruits)  # Output: ['apple', 'banana', 'cherry']

Here, the string is split into a list of fruits using "," (comma) as the delimiter.


Summary:

  • Joining: Combine a list of strings into a single string using a specified delimiter with delimiter.join(list).
  • Splitting: Convert a string into a list of substrings using a specified delimiter with string.split(delimiter).
  • These methods work together to manipulate and organize text data efficiently.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What is the output of the following code: words = ["Hello", "world", "in", "Python"]; " ".join(words)?

Hello world in Python
Hello world in Python
Hello, world, in, Python
Hello/world/in/Python
Check Answer

Which method is used to join a list of strings with a comma as a delimiter?

split()
join()
concat()
merge()
Check Answer

What will be the output of the following code: sentence = "Python is amazing"; sentence.split()?

['Python', 'is', 'amazing']
['Python is amazing']
['Python', 'is amazing']
['Python', 'is', 'amazing', '']
Check Answer

How would you split the string "apple,banana,cherry" into a list of fruits?

Check Answer

What does the .join() method do?

Splits a string into a list
Joins a list into a string
Counts the number of elements
Reverses the order of a string
Check Answer