Python 3 Split and Join String With Examples

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.

The codes will generate the following output.

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.

The codes generate the following output.

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.

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.

And that’s how we split and join strings in Python.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like