How to Split a String in Python?

Splitting a string in Python is done using the split() method. It divides a string into a list based on a specified separator.

Basic Usage

text = 'apple,banana,cherry'
fruits = text.split(',')
print(fruits)  # Output: ['apple', 'banana', 'cherry']

Splitting by Whitespace

By default, split() uses whitespace as the separator:

text = 'Hello World'
words = text.split()
print(words)  # Output: ['Hello', 'World']

Limiting Splits

Use the maxsplit parameter to limit the number of splits:

text = 'a,b,c,d'
result = text.split(',', 2)
print(result)  # Output: ['a', 'b', 'c,d']

Conclusion

The split() method is a fundamental tool for string manipulation in Python. It allows you to parse and process text data effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *