
Syntax: Splitting and Joining Strings
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
-
Create a string
csv_datathat contains some comma-separated values:"Python,Data Science,Machine Learning,AI" -
Split
csv_datainto a list of values and print the list. -
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
> ['Python', 'Data Science', 'Machine Learning', 'AI']
> "Python, Data Science, Machine Learning, AI"
SOLUTION*: Click here for an example solution
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.