How to Split String in Python?

Python Split String

To split a String in Python using delimiter, you can use split() method of the String Class on this string.

In this tutorial, we shall learn how to split a string in Python, with well detailed Python example programs.

Syntax of split()

The syntax of String.split() method is

str.split(separator, maxsplit)

where

  • str is the string which has to be split
  • separator is the delimiter where the string is split. If not provided, the whole string is considered as a single chunk and returned as an element in the list.
  • maxsplit is the maximum number of splits that can be done. If not provided, maximum possible splits are done.

Examples

1. Split given string by comma

In this example, we take a string that has chunks separated by comma. We will split this string using comma as separator and store the result in a variable.

Python Program

str = 'Python,Examples,Programs,Code,Programming'

chunks = str.split(',')
print(chunks)
Run Code Copy

Output

['Python', 'Examples', 'Programs', 'Code', 'Programming']

2. Split string with a constraint on number of splits

In this example, we take a string that has chunks separated by comma. We will split this string using comma as separator and maximum number of chunks as 3.

Python Program

str = 'Python,Examples,Programs,Code,Programming'

chunks = str.split(',', 3)
print(chunks)
Run Code Copy

Output

['Python', 'Examples', 'Programs', 'Code,Programming']

The string is split thrice and hence 4 chunks.

3. Call split() on string with no arguments passed

When no arguments are provided to split() function, one ore more spaces are considered as delimiters and the input string is split.

In this example, we will split a string arbitrary number of spaces in between the chunks.

Python Program

str = '    hello World!    Welcome to  Python     Examples. '

#split function without any arguments
splits = str.split()

print(splits)
Run Code Copy

Output

['hello', 'World!', 'Welcome', 'to', 'Python', 'Examples.']

Summary

In this tutorial of Python Examples, we have gone through different scenarios where we split the string with different types of delimiters, controlled the number of splits, etc.

Code copied to clipboard successfully 👍