What is the purpose of the split() method in Python?
Answer:
The split()
method in Python is used to split a string into a list of substrings, based on a specified separator. The separator can be a character or a string, and the split() method returns a list of the substrings that were separated by the separator.
Here's an example of using the split()
method to split a string into a list of words:
sentence = "This is a sentence." words = sentence.split() print(words) # Output: # ['This', 'is', 'a', 'sentence.']
In this example, the split()
method splits the string sentence
into a list of words, using a whitespace character as the separator.
You can also specify a different separator if you need to split the string based on a different character or string:
email = "user@example.com" parts = email.split("@") print(parts) # Output: # ['user', 'example.com']
In this example, the split()
method splits the string email
into a list of two parts, using the @
character as the separator.
The split()
method is useful when you need to extract individual elements from a string, such as when working with text data.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.