Splitting a String in Python is super easy. You can make use of the split() method to split the string.
How to Split a String into List in Python?
#string is stored in the variable text
text = "Welcome to WTMatter Blog"
#The split string stores into words
words = text.split()
#printing the List of words
About the split() Method
- Method Used – split()
- What it Does – Split any string into Python List.
- Number of Parameters it takes – 2 (Both are optional)
- Return Type – Python List
Syntax & Parameters of split() Method
The syntax for the method is given below.
The first parameter is the separator. It indicates the character from which you want to split the string. It is an optional parameter and if you don’t specify it, it simply assumes the default string splitting character as whitespace. In other words, if you don’t put this parameter, your string will be split by spaces.
The second parameter is max. With this option, you can specify how many occurrences of the splitting symbol should be followed up for string splitting procedure. If there’s a string with 10 whitespaces and you specify max to be 5, then your string will be split into 6 parts by following up the separation procedure of first 5 occurrences of the whitespaces. The default value of this parameter is -1, which indicates to follow up all occurrences of the splitting character.
The following example splits a string into the list by the splitting character comma.
text = "Hello,How,Are,You,Fine"
words = text.split(",")
Likewise, you can use any character as the splitting character according to your requirement and logic.
One more example is given below in which we’ve specified both the optional parameters of the Python split() Method.
text = "Python&String&Split&Made&Easy"
words = text.split("&",3)
The above code splits the string by the symbol ‘&’ but following up only first 3 occurrences.