Python String split() Examples

In Python, we may be required to split a string whether we are parsing data, manipulating text, or processing user input. In this Python tutorial, we will explore various techniques and methods for splitting strings in Python.

The syntax of the split() method in Python is as follows:

listOfSubStrings = originalString.split(sep=None, maxsplit=-1)

It returns a list of substrings resulting from splitting the original string.

1. Default Behavior (Split with Whitespaces, Tabs and Newlines)

The split() method without any arguments splits the string using whitespace characters (spaces, tabs, newlines) as separators.

text = "apple banana orange\ngrape"
fruits = text.split()
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

We can use the maxsplit attribute to control the number of substrings.

text = "apple banana orange\ngrape"
fruits = text.split(maxsplit=2)
print(fruits)  # Output: ['apple', 'banana', 'orange\ngrape']

2. Split a String with New Line

If you want to split a string specifically at newline characters, you can use the splitlines() method.

multiline_text = "Line 1\nLine 2\nLine 3"
lines = multiline_text.splitlines()
print(lines)  # Output: ['Line 1', 'Line 2', 'Line 3']

3. Split a String with a Single Delimiter

To split a string using a single delimiter, use the split() method and specify the delimiter as an argument.

sentence = "Python is a powerful programming language"
words = sentence.split(" ")
print(words)  # Output: ['Python', 'is', 'a', 'powerful', 'programming', 'language']

4. Split a String with Multiple Delimiters

To split a string using multiple delimiters, use the re.split() function from the re module with a regular expression pattern.

import re
text = "apple,banana;orange.grape"
fruits = re.split("[,;.] ", text)
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

5. Split a String with Regex

Regular expressions offer powerful pattern-matching capabilities for splitting strings.

import re
text = "apple  banana  orange grape"
fruits = re.split("\s+", text)
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

6. Split a String and Keep Delimiters

To split a string while keeping the delimiters, you can use the re.split() function with capturing groups.

import re
text = "apple,banana;orange.grape"
fruits = re.split("([,;.]) ", text)
print(fruits)  # Output: ['apple', ',', 'banana', ';', 'orange', '.', 'grape']

7. Conclusion

In this Python tutorial, we learned various techniques and methods for splitting strings in Python. From the basic split() method to more advanced approaches using regular expressions.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.