String split() Method in Python

String Split() Method in Python 

A string is divided into a list using the split() method. The separator can be specified; however, any white space is used by default. We can split() a string in Python very easily. The list will have the specified number of components plus one when maxsplit is specified.

split in python

String 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

Run
#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']

Code 2

Run
#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']

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription