How to use list split() method in Python?
Using the list split() method is very easy, just call the split() function with a string object and pass the separator as a parameter. Here we are using the Python String split() function to split different Strings into a list, separated by different characters in each case.
Example: In the above code, we have defined the variable ‘text’ with the string ‘geeks for geeks’ then we called the split() method for ‘text’ with no parameters which split the string with each occurrence of whitespace.
Python3
text = 'geeks for geeks' # Splits at space print (text.split()) word = 'geeks, for, geeks' # Splits at ',' print (word.split( ',' )) word = 'geeks:for:geeks' # Splitting at ':' print (word.split( ':' )) word = 'CatBatSatFatOr' # Splitting at t print (word.split( 't' )) |
Similarly, after that, we applied split() method on different strings with different delimiters as parameters based on which strings are split as seen in the output.
['geeks', 'for', 'geeks'] ['geeks', ' for', ' geeks'] ['geeks', 'for', 'geeks'] ['Ca', 'Ba', 'Sa', 'Fa', 'Or']
Time Complexity: O(n)
Auxiliary Space: O(n)
Python String split()
Python String split() method splits a string into a list of strings after breaking the given string by the specified separator.
Example:
Python3
string = "one,two,three" words = string.split( ',' ) print (words) |
Output:
['one', 'two', 'three']