Ads by ProfitSence

How Python split () function works ?

Last Updated on Wednesday 5th Oct 2022

string.split() will break and split the string on the argument passed and return all the parts in a list. The list will not include the splitting character.

string.split('","') will break and split the string on every "," and return all the broken parts in a list excluding ","

					print 'Woohoo","There you are'.split(r'","')

					['Woohoo', 'There you are']


You can specify how many parts you want to split your string into by passing an additional parameter

  • Split on all commas and split into n + 1 parts, where n is the number of commas
					print 'Man,From,Mars'.split(',')


The Above Outputs

					['Man', 'From', 'Mars]

  • Split on the first comma and only split into 2 parts.
					print 'Man,From,Mars'.split(',',1)


The Above Outputs

					['Man', 'From Mars]

  • Here I used ' ' as split, so every time a character appears ' ', it splits the string into a new list item.
					'Hi Im from Neptune'.split(' ')


The Above Outputs

					['Hi', 'Im', 'from', 'Neptune']