3 Examples of How to use Python String Split method

3 Examples of How to use Python String Split method

Python String Split method

The Python split method breaks the given string. The given string breaks from the specified separator and returns a list of lines.

In this chapter, you will learn the Split string method and a few examples of using it.

An example of string split

How to use the Split method?

Following is the general syntax of the Split method:

String.split(separator, number_of_lines)

For example

Str.split(‘ , ’ , 2)

If no separator is given, space will be used by default.

Split string method example

The example below uses the split method that breaks the string from comma in the given string and displays the output.

Python string split method

See this example online

The output:

[‘This is Python strings lesson’, ‘ this is split string method’]

String split with number parameter example

The following example limits the number of “splits” by using a number as a parameter in the split method. Even the given string has two commas, the split method will break it into two lines while the second line contains a comma. See the example and output below.

Python split number

See this example online

The output will be:

[‘This is Python strings lesson’, ‘ this is python split string method, with number parameter’]

Iterating over broken strings

As such, the Python split method returns a list of lines, this can be manipulated just like Python lists. The following example uses a for loop to iterate through the returned broken string.

See this example online

The output will be:

This is Python strings lesson

this is python split method

with the number parameter