Split Function in Python

The split function in Python is a versatile method used to divide a string into a list of substrings based on a specified delimiter. By default, it splits on whitespace, making it particularly useful for parsing text data where words are separated by spaces, tabs, or newlines. This function is commonly employed in text processing tasks, such as reading and analyzing the contents of a file.

Basic Usage

The primary use of the split function is to break down a string into a list of words or components. When no delimiter is specified, split defaults to using any whitespace character as the delimiter. This includes spaces, tabs, and newlines. Here is a basic example:

x = "You\t\t can have tabs\t\n \t and newlines \n\n mixed in"
x.split()
# [Output: ['You', 'can', 'have', 'tabs', 'and', 'newlines', 'mixed', 'in']](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/57)

In this example, the string x contains various whitespace characters, and split effectively separates the words into a list.

Specifying a Delimiter

The split function allows for a specific delimiter to be defined, which can be any substring. This is useful when dealing with strings that use a particular character or sequence of characters to separate elements:

x = "Mississippi"
x.split("ss")
# [Output: ['Mi', 'i', 'ippi']](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/57)

Here, the string "Mississippi" is split at each occurrence of "ss", resulting in a list of substrings.

Limiting the Number of Splits

An optional second argument can be provided to split to limit the number of splits performed. This is particularly useful when you want to control the number of resulting substrings, especially when the last field may contain delimiters:

x = 'a b c d'
x.split(' ', 1)
# [Output: ['a', 'b c d']](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/57)

x.split(' ', 2)
# [Output: ['a', 'b', 'c d']](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/57)

x.split(' ', 9)
# [Output: ['a', 'b', 'c', 'd']](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/48)

In these examples, the second argument specifies the maximum number of splits to perform. The resulting list will contain one more element than the number of splits specified.

Practical Application

A practical application of the split function is demonstrated in the following code snippet, which counts the occurrences of words in a file:

Listing 3.1 File wo.py

"""wo module. Contains function: words_occur()"""      #A
# [interface functions              #B](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-3/131)
def words_occur():
    """words_occur() - count the occurrences of words in a file."""
    # Prompt user for the name of the file to use.
    file_name = input("Enter the name of the file: ")
    # Open the file, read it and store its words in a list.
    f = open(file_name, 'r')
    word_list = f.read().split()                              #C
    f.close()
    # Count the number of occurrences of each word in the file.
    occurs_dict = {}
    for word in word_list:
        # increment the occurrences count for this word
        occurs_dict[word] = occurs_dict.get(word, 0) + 1
    # Print out the results.
    print(f"File {file_name} has {len(word_list)} words ({len(occurs_dict)} are unique)") 
    print(occurs_dict)
if __name__ == '__main__':                                     #D
    words_occur()
#A Docstring to document module.
#B Comment to explain code.
#C read returns all the characters in a file, split splits the string on whitespace.
#D common form for running module as command with python wo.py at a command line.

In this example, the split function is used to read the contents of a file and split it into a list of words. The program then counts the occurrences of each word and prints the results, demonstrating a common use case for split in text processing.

FAQ (Frequently asked questions)

What is the result of splitting a string with the split method?