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.
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)
To split a string into a list using a
rsplit method. If no parameter is specified, it works just like the
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)
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)
View all Courses