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()
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 stringstring1 = "she has twelve rocks"#split the stringx = string1.split()#print the listprint(x)
rsplit()
To split a string into a list using a 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 stringstring1 = "hello, i am john, i work in marketing"#split the stringx = string1.rsplit(', ')y = string1.rsplit()#print the listsprint(x)print(y)
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 stringstring1 = "hello\ni am john\ni work in marketing"#split the stringx = string1.splitlines()#print the listprint(x)