The split()
method in Python is used to split a string into a list of substrings based on a delimiter. Here are multiple examples demonstrating its usage.
Example 1: Splitting a String by Space
sentence = "This is an example sentence."
words = sentence.split() # Defaults to splitting by space
print(words)
# Output: ['This', 'is', 'an', 'example', 'sentence.']
Example 2: Splitting a String by a Specific Character
text = "apple,banana,orange,grape"
fruits = text.split(',') # Splitting by comma
print(fruits)
# Output: ['apple', 'banana', 'orange', 'grape']
Example 3: Limiting the Number of Splits
data = "John,Doe,25,New York,USA"
info = data.split(',', 3) # Splitting by comma with a limit of 3 splits
print(info)
# Output: ['John', 'Doe', '25', 'New York,USA']
Example 4: Splitting Lines in a Multi-line String
multiline_text = """This is line 1
This is line 2
This is line 3"""
lines = multiline_text.split('\n') # Splitting by newline character
print(lines)
# Output: ['This is line 1', 'This is line 2', 'This is line 3']
Example 5: Handling Multiple Spaces
text_with_spaces = "This has spaces."
split_spaces = text_with_spaces.split() # Splitting by spaces
print(split_spaces)
# Output: ['This', 'has', 'spaces.']
Example 6: Using Split with List Comprehension
text = "1, 2, 3, 4, 5"
numbers = [int(num) for num in text.split(',')] # Splitting by comma and converting to integers
print(numbers)
# Output: [1, 2, 3, 4, 5]
These examples illustrate how the split()
method can be used with various delimiters, limits, and scenarios to split strings into lists of substrings.