How to Split Strings in Python Using the split() Method?

In Python, the split() method is used to split a string into a list of substrings based on a specified delimiter. It’s a fundamental string manipulation tool.

Basic Usage of split()

The syntax is:

string.split(separator, maxsplit)

Where:

  • separator (optional): The delimiter string. Default is any whitespace.
  • maxsplit (optional): Maximum number of splits. Default is -1 (all occurrences).

Splitting by Whitespace

Example:

text = "Python is awesome"
words = text.split()
print(words)  # Output: ['Python', 'is', 'awesome']

Splitting by a Specific Delimiter

Split a string by commas:

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

Using maxsplit Parameter

Limit the number of splits:

text = "one,two,three,four"
result = text.split(",", 2)
print(result)  # Output: ['one', 'two', 'three,four']

Splitting Lines

Use splitlines() to split a string into a list at line breaks:

multiline_text = "Line1\nLine2\nLine3"
lines = multiline_text.splitlines()
print(lines)  # Output: ['Line1', 'Line2', 'Line3']

Conclusion

The split() method is an essential tool for string manipulation in Python, allowing you to divide strings into manageable parts.

Leave a Reply

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