How to split a string in different ways using Python

Python is an open-source programming language that provides support for a multitude of operations.

There are a number of built-in methods that Python provides for the manipulation of string variables, including splitting a string in different ways. Let’s take a look at three of these methods.

Split a string using split()

The standard way to split a string is to split it into a list where each word is an item. This is done using the split() method. A separator string can be specified, with the default separator being whitespace.

In the code block below, the string is split with whitespace as the separator, which results in a list in which the items are the separate words of the string.

#initialize the string
string1 = "she has twelve rocks"
#split the string
x = string1.split()
#print the list
print(x)

Split a string using rsplit()

To split a string into a list using a commafollowed by a space character as the separator string, we use the rsplit method. If no parameter is specified, it works just like the split() method.

In the code block below, we split the string in two ways, first using the oxford comma as the separator, and second using the default separator.

#initialize the string
string1 = "hello, i am john, i work in marketing"
#split the string
x = string1.rsplit(', ')
y = string1.rsplit()
#print the lists
print(x)
print(y)

Split a string using splitlines()

To split a string into a list where each line of the string is an item of the list, we use the splitlines() method. Line breaks in the string serve as the separator when splitting.

In the code below, the string is split at the line breaks and each line becomes a separate item in the string.

#initialize the string
string1 = "hello\ni am john\ni work in marketing"
#split the string
x = string1.splitlines()
#print the list
print(x)

Free Resources