If you want to break a large string into a small number of strings (or) chunks, you can use string split() method in python. This method is totally different concatenation, which is used to merge and combine strings into one.
This split function divides the string into splits and adds data to the array string with the help of the defined separator. If there is no separator defined when you call the split function, by default, white space is used.
Separator: Separator is defined as a character which is placed between every variable.
Max Split: It is a parameter in which the number is given that as the maximum number of splits should be done in a string. If this max split is not provided there is no limit for the splitting of a string.
The default max limit will be “-1”, which is known as all occurrences.
The result will be in the form of breakdown strings from the given string with the specified separator.
Split the string using space
txt = " hi my name is David" a = txt.split() print(a)
Split the string using the comma
txt = (" tea, coffee, milk") a = text.split(",") print(a)
Split the string using Hash(#)
txt = "#orange#strawberry#grapes#banana" a = text.split("#") print(a)
['hi ', 'my name is David'] ['tea', 'coffe ', 'milk' ] ['orange', 'strawberry', 'grapes', 'banana']
Split the string using Max split
txt = “hi, my name is David, I am a blogger” #maxsplit 3 print(txt.split(‘ , ‘ ,3)) #maxsplit 2 print(txt.split(‘ , ‘ , 2)) #maxsplit 1 print(txt.split(‘, ‘ , 1)) #maxsplit 0 print(txt.split(‘. ‘, 0)
[ ‘‘hi’, ‘ my name is David’, ‘I am a blogger’] [ ‘‘hi’, ‘my name is David’, I am a blogger’ ] [ ‘‘hi’, my name is David, I am a blogger’ ] [‘hi, my name is David, I am a blogger’]
In this article, we have seen why the split() method is used in Python programming language and in how many cases split can be used. Hope you are clear with the concepts after going through this article. Please does comment if you have any suggestions.
Free Demo for Corporate & Online Trainings.