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.
The syntax of String.split() method is
- 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.
Example 1: Split String
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.
str = 'Python,Examples,Programs,Code,Programming' chunks = str.split(',') print(chunks)
['Python', 'Examples', 'Programs', 'Code', 'Programming']
Example 2: Split String with limited 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.
str = 'Python,Examples,Programs,Code,Programming' chunks = str.split(',', 3) print(chunks)
['Python', 'Examples', 'Programs', 'Code,Programming']
The string is split thrice and hence 4 chunks.
Example 3: Split String with no arguments
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.
str = ' hello World! Welcome to Python Examples. ' #split function without any arguments splits = str.split() print(splits)
['hello', 'World!', 'Welcome', 'to', 'Python', 'Examples.']
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.