String split() Method in Python

Split() Method in Python 

Split() Method returns a list of string after breaking the given string by the given separator. 

Example : 

  • s= ‘A,b,C’
    • [  ‘A’ , ‘b’ , ‘C’ ]
String split() method in Python

Syntax : 

  str.split(separator, maxsplit)

  Parameters :

  separator: This is a delimiter. The string splits at this specified separator. It is not provided then any white space is a separator.

  maxsplit: It is a number, which tells us to split the string into maximum of the provided number of times. If it is not provided then
there is no limit.

Returns: Returns a list of strings after breaking the given string by the specified separator.

  • Let’s understand this with few codes.

Code #1

#python Program 
s=‘PrepInsta Prepster’

#split at whitespace 
print(s.split())

#split at ‘-‘ 
s=‘Prep-Insta-Prep-ster’ 
print(s.split(‘-‘))

#split at ‘,’ 
s=‘PrepInsta,is,for,Prepsters’
print(s.split(‘,’))

Output :

['PrepInsta', 'Prepster']
['Prep', 'Insta', 'Prep', 'ster']
['PrepInsta', 'is', 'for', 'Prepsters']
#python Program 
s=‘PrepInsta;Prepster’

#split at ‘;’ and maxsplit is 0
print(s.split(‘;’,0))

#split at ‘-‘  and maxsplit is 2
s=‘Prep-Insta-Prep-ster’ 
print(s.split(‘-‘,2))

#split at ‘,’  and maxsplit is 4
s=‘PrepInsta,is,for,Prepsters’
print(s.split(‘,’ , 4))

Output : 

['PrepInsta;Prepster']
['Prep', 'Insta', 'Prep-ster']
['PrepInsta', 'is', 'for', 'Prepsters']