This post shows how to split and join strings in Python. String manipulation is one of the everyday operations our programs do in any programming language. Python is no different. We used Python 3.7.0 for the sample codes in this post.
Split Strings In Python
When we want to split a string, we need to know how to divide and use what characters. These characters are part of the string we want to break. For instance, we could separate a sentence by space, and the output would be a collection of sub-strings. These sub-strings had spaces between them. Consider the following codes.
Split String By Space
The following codes split a string by space. Splitting by space is the default behavior of the Python split function.
1 2 3 | sentence = 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout' words = sentence.split() print(words) |
The codes will generate the following output.
1 | ['It', 'is', 'a', 'long', 'established', 'fact', 'that', 'a', 'reader', 'will', 'be', 'distracted', 'by', 'the', 'readable', 'content', 'of', 'a', 'page', 'when', 'looking', 'at', 'its', 'layout'] |
Split String By Using Another Character Or String
We could use a single character or substring to split a string. Let’s say we want to split by the “that” word.
1 2 3 | sentence = 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout' words = sentence.split('that') print(words) |
The codes generate the following output.
1 | ['It is a long established fact ', ' a reader will be distracted by the readable content of a page when looking at its layout'] |
Join Strings In Python
Sometimes we need to join strings together to form a new string. In programming, in general, we join strings more than we split them. To concatenate strings in Python, we use the join function. Consider the following codes. The way to join strings is to use the string object’s join function.
1 2 3 4 | words = ['It is a long established fact ', ' a reader will be distracted by the readable content of a page when looking at its layout'] delimeter = '*****' sentence = delimeter.join(words) print(sentence) |
The collection of strings to join usually comes in the form of an array. Then, we pass a variable referring to an array of strings to the join function. We can even specify the delimiter that does between the strings in the final form.
When we run the Python codes, we get the following output. The final single string has the line “*****” added to it. If we don’t want asterisks, we could use a space instead.
1 | It is a long established fact ***** a reader will be distracted by the readable content of a page when looking at its layout |
And that’s how we split and join strings in Python.