Join Regular Classroom : Visit ClassroomTech

Python String – split() method

It is a method in string that splits the given string into lists by a separator into segments. The default separator is whitespace. The separator can be specified within the brackets. It is a very powerful and useful method in Python string, used almost in all intermediate programs. The return data type is a list.

Syntax:

string.split(separator, max_split)
max_split (optional): specifies the number of splits to be performed. By default it is -1 (all occurrences)

Example 1:

s = “CODE, hustle
x = s.split()
print(x)

Output:

[‘CODE,‘, ‘hustle‘]

Explanation:

Here the string is split into two items by a space as the separator and returned it as a list.

Example 2:

s = “CodeWindow,code,hustle,repeat
x = s.split(“,“)
print(x)

Output:

[‘CodeWindow‘, ‘code‘, ‘hustle‘, ‘repeat‘]

Explanation:

Here the string is split into two items by “,” as the separator and returned it as a list.

Example 3:

s = “CodeWindow,code,hustle,repeat
x = s.split(“,“,1)
print(x)

Output:

[‘CodeWindow‘, ‘code,hustle,repeat‘]

Explanation:

Here the max_split is 1 so, it returned a list with 2 items (“,” as a separator).

You Missed
Also Checkout