How to Split String in Python?

Python String Split

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?

Example Code

#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
print(words)

Python String Split Example

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.

string.split(separator, max)

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.

More Examples

The following example splits a string into the list by the splitting character comma.

text = "Hello,How,Are,You,Fine"

words = text.split(",")

print(words)

Python String Split Example With Splitting Character As Comma

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)

print(words)

Python String Split Example With The Use Of Both Parameters Split And Max

The above code splits the string by the symbol ‘&’ but following up only first 3 occurrences.

Leave a Reply

Your email address will not be published. Required fields are marked *