Python is a popular programming language that provides many built-in functions to handle strings. One of the commonly used functions is the split()
function, which can split a string into multiple substrings according to the specified delimiter. This article will introduce how to use the split()
function in Python 3.x.
In Python, the split()
function is a built-in function of the string class. Its basic syntax is as follows:
string.split(separator, maxsplit)
Among them, separator
is a string used to specify the delimiter, which defaults to a space character. maxsplit
is an optional parameter used to specify the maximum number of splits. The default is -1, which means there is no limit to the number of splits.
The following is a simple example of how to use the split()
function to split a string according to spaces:
str = "Hello World" result = str.split() print(result)
The output result is:
['Hello', 'World']
In this example, we assign the string "Hello World" to the variable str
, and then use the split()
function to split it. Since no delimiter is specified, the space character is used by default. The final result is a list containing two substrings.
If we want to use other delimiters to split the string, we only need to pass the delimiter as a parameter of the split()
function. For example, if we want to split a comma-delimited string, we can use the following code:
str = "apple,banana,orange" result = str.split(",") print(result)
The output will be:
['apple', 'banana', 'orange']
In this example, we use comma as the delimiter Passed to the split()
function, this realizes the function of splitting strings according to commas.
In addition to specifying the separator, we can also limit the number of splits through the maxsplit
parameter. If we want to split only the first two substrings of the string, we can set maxsplit
to 2, as shown below:
str = "apple,banana,orange" result = str.split(",", 2) print(result)
The output result is:
['apple', 'banana', 'orange']
In this In the example, the value of the maxsplit
parameter is 2, so the string will only be split into three substrings at most.
To summarize, the split()
function in Python 3.x is a very useful function that can split a string into multiple substrings based on the specified delimiter. At the same time, we can also limit the number of splits through the maxsplit
parameter. By rationally using the split()
function, we can handle string splitting operations more conveniently.
The above is the detailed content of How to use the split() function in Python 3.x to split a string according to the specified delimiter. For more information, please follow other related articles on the PHP Chinese website!