Register Login

Use of Python String Split() Method

Updated Oct 14, 2019

In Python split() method breaks the given string with defined separator and returns the list of string.

Syntax:

string.split(separate, maxsplit)

Parameters:

separate: (Optional): Defined Separator to split the string, if there is no separator defined, white space will be treat as default separator.
maxsplit: (Optional): It is a integer value to specify number of times to split, By Default there is no limit.

Returns: List of string after breaking the given sting by the defined separator.

Example:

# Python program to explain split() method

# initialized string
string = "Hello this is Stechies"

# split method with no optional values
print(string.split())


string = "Hello,this,is,Stechies"

# split with separator comma ','
print(string.split(','))

# split with separator ',' and maxsplit = 2
print(string.split(',', 2))

# split with separator ',' and maxsplit = 0
print(string.split(',', 0))

Output:

['Hello', 'this', 'is', 'Stechies']
['Hello', 'this', 'is', 'Stechies']
['Hello', 'this', 'is,Stechies']
['Hello,this,is,Stechies']

Split() Method with Multiple Delimiters or Regex

Example:

# Python program to explain split() method with regular expressions

# import regular expression library 
import re

# initialized string
string = "Hello, this; is\nStechies"

output=re.split('; |, |\*|\n',string)
print(output)

Output:

['Hello', 'this', 'is', 'Stechies']

Example:

# Python program to explain split method and output in string variable

# initialized string
string = "Hello,this,is,Stechies"

# split with separator comma ','
# save output in string variable
a,b,c,d=string.split(',')

print('Value 1: ',a)
print('Value 1: ',b)
print('Value 1: ',c)
print('Value 1: ',d)

Output:

Value 1:  Hello
Value 1:  this
Value 1:  is
Value 1:  Stechies

 


×