Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Syntax: Splitting and Joining Strings

check

Splitting and re-joining Python strings based on specific patterns.


In Python, you can split a string into a list of substrings using the split() method. Similarly, you can join a list of strings into a single string using the join() method. These functions are very useful in data preprocessing and text mining tasks.

Splitting Strings

The split() method in Python splits a string into a list where each word is a separate item in the list.

text = "Hello, how are you doing today?"
words = text.split()
print(words)

> ['Hello,', 'how', 'are', 'you', 'doing', 'today?']

Joining Strings

The join() method in Python takes all items in an iterable and joins them into one string. A string must be specified as the separator.

words = ['Python', 'is', 'an', 'awesome', 'language']
sentence = ' '.join(words)
print(sentence)

> "Python is an awesome language"

Practice: Splitting and Joining Strings

  1. Create a string csv_data that contains some comma-separated values: "Python,Data Science,Machine Learning,AI"

  2. Split csv_data into a list of values and print the list.

  3. Then join the list back into a string with each value separated by a comma and a space. Print the new string.

Run your code and confirm that the output is a list of values and a comma-separated string.

HINT*: Click here for a hint
*Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.
> ['Python', 'Data Science', 'Machine Learning', 'AI']
> "Python, Data Science, Machine Learning, AI"
SOLUTION*: Click here for an example solution
*Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
csv_data = "Python,Data Science,Machine Learning,AI"
values = csv_data.split(',')
print(values)
joined_string = ', '.join(values)
print(joined_string)

Great work! Being able to split and join strings is crucial when dealing with text data, as it provides a simple way to format and analyze the data.