Splitting and Joining strings in Python (19/100 Days of Python)

Martin Mirakyan
2 min readJan 20, 2023

--

Day 19 of the “100 Days of Python” blog post series covering how to split and join strings

The str.split() and str.join() methods in Python are used to manipulate strings. The str.split() method is used to split a string into a list of substrings based on a specified separator:

sentence = 'Hello World!'
words = sentence.split(' ')
print(words) # ['Hello', 'World!']

By default the split is performed on any whitespace. So, if we call the split function without providing a separator, it will split the string by whitespace:

message = '''Hello my dear friend,
Hope you are doing well.
How is life?
Hope to see you soon!
'''
print(message.split()) # ['Hello', 'my', 'dear', 'friend,', 'Hope', 'you', 'are', 'doing', 'well.', 'How', 'is', 'life?', 'Hope', 'to', 'see', 'you', 'soon!']

You can also use split() method to split string based on multiple separators, using the re module (regular expressions — which we’ll cover later in the series):

import re

sentence = 'Hello, Anna! How are you?' # Initial sentence
words = re.split(r'[, !?]', sentence) # Split by a comma, space, exclamation mark and a question mark
print(words) # ['Hello', '', 'Anna', '', 'How', 'are', 'you', '']

Joining a list of strings

On the other hand, str.join() method is used to join a list of strings into a single string, using a specified separator:

words = ['Hello', 'Anna!', 'How', 'are', 'you', '?']
sentence = ' '.join(words) # Join with a space between each pair of items
print(sentence) # `Hello Anna! How are you ?`

In the above example, ' ' is the separator which is used to join the list of strings. We can use any string in its place to join the words together with the specified string in between:

sentence = 'Hi Anna! How are you doing?'
words = sentence.split('!') # ['Hi Anna', ' How are you doing?']
words[0] = 'Hi Python' # Change the first element in the list
new_sentence = ' -- '.join(words)
print(new_sentence) # Hi Python -- How are you doing?

In this example, we first use split() to split the sentence into a list of parts. Then we change the first part to "Hi Python". Finally, we use join() to join the list of parts back into a single string.

So, the split() and join() methods in Python are powerful tools for manipulating strings. The split() method can be used to break a string into a list of substrings, while the join() method can be used to join a list of strings into a single string.

What’s next?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet