Last modified: Jun 05, 2023 By Alexander Williams

How to Use Python Split() in Examples

In Python, the split() method is a function that splits a string into a list of substrings based on a specified delimiter. In this tutorial, we will learn how to use the split() function with examples.

Splitting a sentence into words

sentence = "The quick brown fox" # Sentence

words = sentence.split() # Split

print(words) # Result

Output:

['The', 'quick', 'brown', 'fox']

The example above splits the sentence into individual words using the split() method and prints the resulting words.

Splitting a comma-separated string into a list

csv = "apple,banana,orange"

fruits = csv.split(",")

print(fruits)

Output:

['apple', 'banana', 'orange']

The code example splits the string by comma (",").

Splitting a multi-line string into lines

multiline = "Line 1\nLine 2\nLine 3"

lines = multiline.split("\n")

print(lines)

Output:

['Line 1', 'Line 2', 'Line 3']

The code example splits with the delimiter "\n" (newline character).

Splitting a string and limiting the number of splits

string = "One Two Three Four Five"

words = string.split(maxsplit=2)

print(words)

Output:

['One', 'Two', 'Three Four Five']

The code example splits with the optional argument maxsplit=2. This argument limits the split to a maximum of two splits, resulting in a list containing three elements.

Conclusion

These examples demonstrate how the split() method can be used to split a string into substrings based on various delimiters. You can customize the delimiter, specify the maximum number of splits, and process the resulting substrings as needed.

Here are some articles about the split() method if you want more information on how to use it:

Read File and Split The Result in Python

Python Split By Multiple Characters