Python3 split() Method

Python3 字符串Python3 Strings


Description

The split() method slices a string by a specified separator. This method splits the string into substrings and returns a list composed of these substrings.

If the second parameter num is specified, the string is split into num+1 substrings.

The split() method is especially suitable for splitting a string into multiple parts based on a specific separator.

Syntax

Syntax of the split() method:

str.split(str="", num=string.count(str))

Parameters

  • str -- Separator, defaults to all whitespace characters, including spaces, newlines (\n), tabs (\t), etc.
  • num -- Number of splits. If this parameter is set, the string is split into at most maxsplit+1 substrings. The default is -1, meaning all occurrences are split.

Return Value

Returns a list of the split strings.

Examples

The following examples demonstrate how to use the split() function:

Example (Python 3.0+)

#!/usr/bin/python3 str = "this is string example....wow!!!" print (str.split()) # By default, uses spaces as the separator print (str.split('i',1)) # Uses i as the separator print (str.split('w')) # Uses w as the separator

The output of the above examples is as follows:

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']

The following example uses # as the separator, sets the second parameter to 1, and returns two parameter lists.

Example (Python 3.0+)

#!/usr/bin/python3 txt = "Google#Example#Taobao#Facebook" # The second parameter is 1, returns two parameter lists x = txt.split("#", 1) print(x)

The output of the above example is as follows:

['Google', 'Example#Taobao#Facebook']

Python3 字符串Python3 Strings

Other Extensions