Python split() Method Explained with Examples
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
Python's split() method breaks a string into a list of substrings. Its syntax is str.split(sep=None, maxsplit=-1). When sep is omitted or None, Python splits on any run of whitespace and removes leading and trailing whitespace. When sep is supplied, it is treated as an exact delimiter, and consecutive delimiters can produce empty strings in the result. maxsplit controls how many splits occur: the default -1 means no limit, 0 returns the original string as a single-item list, and a positive value leaves the unsplit remainder in the final element. The method always returns a new list of strings and does not modify the original string, since strings are immutable.
For example, 'a,b,c'.split(',') returns ['a', 'b', 'c'], while 'one two three'.split(maxsplit=1) returns ['one', 'two three']. Default whitespace splitting is useful for tokenizing text: ' Python split '.split() returns ['Python', 'split'].
The time complexity is O(n), where n is the length of the input string, because Python must scan the string once. Space complexity is O(n) for the returned list and substrings. Use split() for parsing CSV-like data, processing words, and limiting splits efficiently.