String Split in Python

Python string method split() inputs a string value & outputs a list of words contained within the string by separating or splitting the words on all the whitespaces by default. It also has an optional argument for limiting the number of splits.

The split() method converts the string into other data types like lists by breaking a string into pieces. Python provides us with two methods: .split() and .rsplit().

Both .split(), & .rsplit() take a separating element by which we are splitting the string, & a maxsplit tells us the maximum number of substrings we want.

Example of Using the .split() Method

Let’s split the above string using the .split() method. Notice that the .split() method starts splitting at the left of the string. It takes two arguments: separator sep & maximum splits of the string maxsplit.

Example of Splitting Strings Into Many Substrings

In the below example, we will split the string file into many substrings at line boundaries. Then, we will print out the resulting variable file_split. Finally, complete the for-loop to split the strings into many substrings using commas as a separator element.

When we run the above code, it produces the following result:


Data Scientist & Machine Learning Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store