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.
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.
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 = "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']
Lessons in this chapter · String Formatting Made Easy
- 1. Inserting Variables into Strings with the format() Function
- 2. Tips for Using `format()` Function - indexError
- 3. Displaying Integers with the format() Function
- 4. Handling Floating-Point Numbers with the format() Function
- 5. Multiple-choice quiz
- 6. Case Conversion Methods upper() and lower()
- 7. Removing Leading and Trailing Whitespace with the strip() Function
- 8. String Composition Verification with isOOO() Methods
- 9. Finding the Position of a Specific Character Using find() and rfind()
- 10. Using the split() Method for Strings
- 11. How to Check if a Specific Character Exists in a String
- 12. Multiple-choice quiz
- 13. How to Format Strings with f-Strings
- 14. Comparison of format() Function and f-Strings
- 15. Using the `input` Function to Receive User Input
- 16. Indicating Invalid Values with ValueError
- 17. Coding Quiz - Splitting Strings
- 18. Multiple-choice quiz
- 19. Fill-in-the-blank quiz
What is the default delimiter for the split() function?
Comma
Newline character
Space
Semicolon
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help