Open In App
Related Articles

Python String split()

Improve Article
Improve
Save Article
Save
Like Article
Like

Python String split() method in Python split a string into a list of strings after breaking the given string by the specified separator.

Python String split() Method Syntax

Syntax : str.split(separator, maxsplit)

Parameters :

  • separator: This is a delimiter. The string splits at this specified separator. If 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 provided number of times. If it is not provided then the default is -1 that means there is no limit.

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

Python String split() Method Example

Python3




string = "one,two,three"
words = string.split(',')
print(words)


Output:

['one', 'two', 'three']

Time Complexity: O(n)
Auxiliary Space: O(n)

How split() works in Python?

Here we are using the Python String split() function to split different Strings into a list, separated by different characters in each case.

Python3




text = 'geeks for geeks'
  
# Splits at space
print(text.split())
  
word = 'geeks, for, geeks'
  
# Splits at ','
print(word.split(','))
  
word = 'geeks:for:geeks'
  
# Splitting at ':'
print(word.split(':'))
  
word = 'CatBatSatFatOr'
  
# Splitting at t
print(word.split('t'))


Output :

['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
['geeks', 'for', 'geeks']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']

Time Complexity: O(n)
Auxiliary Space: O(n)

How does split() work when maxsplit is specified?

The maxsplit parameter is used to control how many splits to return after the string is parsed. Even if there are multiple splits possible, it’ll only do maximum that number of splits as defined by maxsplit parameter.

Python3




word = 'geeks, for, geeks, pawan'
  
# maxsplit: 0
print(word.split(', ', 0))
  
# maxsplit: 4
print(word.split(', ', 4))
  
# maxsplit: 1
print(word.split(', ', 1))


Output :

['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks', 'for, geeks, pawan']

Time Complexity: O(n)
Auxiliary Space: O(n)


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Mar, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials