How to Use the Python split() String Method
In this tutorial, you'll learn how to use the Python split() string method. The split() splits a string and returns a list of strings.
Python split() String Method Syntax
The syntax of the Python split() method is as follows:
split(separator [, maxsplit])
The split() Method Parameters
- separator: Optional. A string delimiter used to split the string. Whitespace will be a separator, and multiple whitespaces are treated as a single separator if the separator is not specified or None.
- maxsplit: Optional. The maximum number of splits. The default value is -1. There is no limit on the number of splits if it's not specified.
Examples
Example 1
The following code splits a string into a list:
string = "This tutorial teaches you how to use the string methods!"
list = string.split()
print("The list of strings is", list)
Output:
The list of strings is ['This', 'tutorial', 'teaches', 'you', 'how', 'to', 'use', 'the', 'string', 'methods!']
Example 2
The following code illustrates an example of how to split a string into a list separated by a single space:
string = "This tutorial teaches you how to use the string methods!"
list = string.split(" ")
print("The list of strings is", list)
Output:
The list of strings is ['This', '', '', '', '', '', 'tutorial', '', '', '', '', 'teaches', 'you', 'how', 'to', 'use', 'the', 'string', 'methods!']
Example 3
The following code splits a string into a list, with a maximum of three items.
string = " This tutorial teaches you how to use the string methods!"
list = string.split(None, 2)
print("The list of strings is", list)
Output:
The list of strings is ['This', 'tutorial', 'teaches you how to use the string methods!']
Example 4
The following code splits a string into a list of strings with a maximum of four items, separated by a vertical bar:
string = "Python Programming|C++ Programming|C# Programming|Java Programming|PHP Programming|C Programming|Visual Basic Programming"
list = string.split("|", 4)
print("The list of strings is", list)
Output:
The list of strings is ['Python Programming', 'C++ Programming', 'C# Programming', 'Java Programming', 'PHP Programming|C Programming|Visual Basic Programming']
In this tutorial, you've learned how to use the Python split() string method. The Python split() string method splits a string into a list of strings, separated by a separator.