Python String Split() Method
Example
Split the string into a list where each word is an item in the list:
txt = "welcome to China" x = txt.split() print(x)
Definition and Usage
The split() method splits a string into a list.
You can specify a delimiter; the default delimiter is any whitespace character.
Note:If max is specified, the list will contain one more element than the specified number.
Syntax
.split(separator, max)
Parameter Value
Parameter | Description |
---|---|
separator | Optional. Specifies the delimiter to be used when splitting the string. The default value is a blank character. |
max | Optional. Specifies the number of splits to be performed. The default value is -1, which means "all occurrences". |
More Examples
Example
Split the string using a comma followed by a space as a delimiter:
txt = "hello, my name is Bill, I am 63 years old" x = txt.split(", ") print(x)
Example
Use the hash character as a delimiter:
txt = "apple#banana#cherry#orange" x = txt.split("#") print(x)
Example
Split the string into a list of up to 2 items:
txt = "apple#banana#cherry#orange" Set the max parameter to 1, and it will return a list containing 2 elements! x = txt.split("#", 1) print(x)