Categories
Python Answers

How to split a string and keep the separators with Python?

Spread the love

Sometimes, we want to split a string and keep the separators with Python.

In this article, we’ll look at how to split a string and keep the separators with Python.

How to split a string and keep the separators with Python?

To split a string and keep the separators with Python, we can use the re.split method with the '(\W)' pattern.

For instance, we write:

import re

a = re.split('(\W)', 'foo/bar spam\neggs')
print(a)

We call re.split with '(\W)' and the string we want to split into an array of substrings and assign the array to a.

Therefore, a is ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs'].

Conclusion

To split a string and keep the separators with Python, we can use the re.split method with the '(\W)' pattern.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *