Split a string with delimiters in Python
This post will discuss how to split a string with delimiters in Python.
1. Using re.split() function
A simple solution to split a string by the pattern’s occurrences is using the built-in function re.split(). The pattern can consist of one or more delimiters:
⮚ Split on single delimiter
To split a string with a single delimiter, you can simply pass that delimiter to the re.split() function.
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'Hello,World' res = re.split(',', s) # split with comma print(res) # ['Hello', 'World'] |
⮚ Split on multiple delimiters
To split with multiple delimiters, you can do like:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'https://techiedelight.com' res = re.split('[:/ .]+', s) # split with colon, slash, space and period print(res) # ['https', 'www', 'techiedelight', 'com'] |
⮚ Split on non-alphanumeric characters
To split the string on non-alphanumeric characters, you can use the special character \W, equivalent to [^a-zA-Z0-9_].
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'https://techiedelight.com' res = re.split('\W+', s) # split on non-alphanumeric characters, excluding _ print(res) # ['https', 'www', 'techiedelight', 'com'] |
To split on underscore as well, you can use the following code:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'https://techiedelight.com' res = re.split('[^a-zA-Z0-9]+', s) # split on non-alphanumeric characters print(res) # ['https', 'www', 'techiedelight', 'com'] |
2. Using re.findall() function
Another alternative is to use the re.findall() function, which returns all non-overlapping matches of a pattern in a string. The following code example demonstrates its usage by using the special character \w, which matches the alphanumeric characters and the underscore.
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'https://techiedelight.com' res = re.findall('\w+', s) print(res) # ['https', 'www', 'techiedelight', 'com'] |
The special character \w is the opposite of \W, i.e., it is equivalent to [a-zA-Z0-9_]. To split on underscore as well, you can use the following code:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'https://techiedelight.com' res = re.findall('[a-zA-Z0-9]+', s) print(res) # ['https', 'www', 'techiedelight', 'com'] |
That’s all about splitting a string with delimiters in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)