Lecture

Using the split() Method for Strings

The split() method divides a string into multiple parts based on a specified character.

By default, it splits the string using spaces as the delimiter and returns the result in the form of a list.

What is a List? : A data type that manages multiple pieces of data as a single entity. Lists are expressed with square brackets [], and each piece of data is separated by commas.


Using the split() Method
text = "Apple Banana Cherry" splitted_text = text.split() # ['Apple', 'Banana', 'Cherry'] print(splitted_text)

If you wish to split the string based on a specific character or substring, you can provide that substring as an argument to the split() method.

For example, a string using commas (,) as delimiters can be split using split(",") as shown below.

What is a Delimiter? : A character or string that specifies the boundary between different parts of data.


Using Comma (,) as a Delimiter
text = "Apple,Banana,Cherry" # Using comma as a delimiter splitted_text = text.split(",") # ['Apple', 'Banana', 'Cherry'] print(splitted_text)

Where to Use the split() Method?

The split() method is commonly used to divide sentences or paragraphs into individual words or to process data separated by delimiters, such as in CSV files.

CSV Data Splitting Example
csv_data = "Name,Age,City\nJohn,30,NewYork\nSusan,45,LosAngeles" # Splitting data using newline character \n as delimiter lines = csv_data.split("\n") # Processing each line of the split data for line in lines: # Splitting data using comma as a delimiter fields = line.split(",") print(fields) # Output: # ['Name', 'Age', 'City'] # ['John', '30', 'NewYork'] # ['Susan', '45', 'LosAngeles']
Mission
0 / 1

What is the default delimiter for the split() function?

Comma

Newline character

Space

Semicolon

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result