In Python, the split() method of a string is used to split the string into a list of substrings based on a specified delimiter. By default, the split() method uses any whitespace as the delimiter (spaces, tabs, newlines, etc.) and removes extra whitespace from both ends of the string.
Here's we you can use the split() method in Python:
# Define a string
my_string = "Hello world! This is a string."
# Split the string into a list of words
words = my_string.split()
# Print the list of words
print(words)
In the example above, split() splits the string into words wherever there is whitespace, and the result is a list of words: ['Hello', 'world!', 'This', 'is', 'a', 'string.
'].
You can also specify a different delimiter for splitting the string. For example, you can split a comma-separated string by specifying ,
as the delimiter:
# Define a comma-separated string
csv_string = "apple,banana,orange,grape"
# Split the string using a comma as the delimiter
fruits = csv_string.split(',')
# Print the list of fruits
print(fruits)
In this example, csv_string.split(',')
splits the string using , as the delimiter, resulting in a list of fruits: ['apple', 'banana', 'orange', 'grape'
].
You can also limit the number of splits by specifying the maxsplit
parameter:
# Define a string
sentence = "This is a test sentence."
# Split the string into at most 2 parts
parts = sentence.split(' ', maxsplit=2)
# Print the list of parts
print(parts)
In the example above, sentence.split(' ', maxsplit=2)
splits the string at most 2 times, resulting in a list with 3 parts: ['This', 'is', 'a test sentence.'
].
Overall, the split()
method is a useful tool for breaking a string into a list of substrings based on a specified delimiter