欢迎访问宙启技术站
智能推送

Python中split()函数的使用方法是什么?

发布时间:2023-06-15 20:51:52

The split() function in Python is used to divide a string into smaller parts, called tokens, based on a specific delimiter. The function returns a list of the tokens that were separated from the original string.

The syntax for using the split() function is as follows:

string.split(separator, maxsplit)

The first parameter is the separator, which is the character or string that separates the tokens in the original string. If the separator is not provided, the default separator is whitespace (i.e. space, newline, tab, etc.).

The second parameter is the optional maxsplit, which specifies the maximum number of splits to be made. If maxsplit is not provided, all occurrences of the delimiter will be split. If maxsplit is specified, the function will only split up to that number of times.

Here's an example of using the split() function:

string = "Hello, World!"

tokens = string.split(", ")

print(tokens)

Output:

['Hello', 'World!']

In this example, the comma followed by a space (", ") is the separator. The split() function divides the original string into two tokens based on this separator. The resulting list contains the two tokens as separate strings.

Another example of using split() with a different separator:

string = "Apple|Banana|Cherry|Mango"

tokens = string.split("|")

print(tokens)

Output:

['Apple', 'Banana', 'Cherry', 'Mango']

In this example, the vertical bar ("|") is used as the separator. The split() function divides the original string into four tokens and returns a list containing each of the four tokens as separate strings.

It's important to note that the split() function does not modify the original string. Instead, it returns a new list containing the separated tokens. If the separator is not found in the original string, the split() function returns a list with a single element that is equal to the original string.

Overall, the split() function is a very useful tool for dividing a string into smaller parts based on a specific separator. It's important to keep in mind the syntax and optional parameters of the function to get the desired results.