Python String Split Example | split() Method Tutorial
Python String Split Example | split() Method Tutorial is today’s topic. In any programming language, working with a string datatype is normal, and there are two most essential operations regarding string which is String Concatenation and String Split. The split() method splits a string into the list. In this example, we will see how we can split the string by a separator. The split() method returns the list of strings after breaking the given string by a specified separator.
Python String Split Example
In Python, we can use the split() method to split the string. What it does is split or break up the string and add the data to a string list using a defined separator. If the separator is not specified then white space will be considered as a separator by default. In simpler terms, the separator is the defined character that will be placed between each item.
The syntax for Python String split() method is following.
The separator parameter is the delimiter which splits the string from a specified character.
The limit parameter is the limit which is optional, and if provided then it splits the string into the maximum of the provided number of times.
Provide No Parameter in Split() Method
Let us see an example, where we do not provide any parameter in the split() method.
# app.py strA = 'Welcome! Wish 2019 Will Be A Great Year' splitedOut = strA.split() print(splitedOut)
The output is following.
Provide A Separator in Split() Method
Now, let us take an example to provide a separator and see the output.
# app.py strA = 'Welcome! Wish 2019 Will Be A Great Year' splitedOut = strA.split('!') print(splitedOut)
In the output, it has split the string from the! Separator.
Provide Both Parameters
See this case where we provide both the parameters.
# app.py strA = 'Welcome! Wish 2019 Will Be A Great Year' splitedOut = strA.split(' ', 3) print(splitedOut)
In the above code, we have defined the space as a separator, and we will split at max three times.
When the limit parameter is specified, the list will contain the specified number of items plus one. In the above example, we have put the limit of 3. That is why we get the list of items 4.
Finally, Python String Split Example | split() Method Tutorial is over.