Split a string on whitespace in Python
This post will discuss how to split a string on whitespace in Python. The result should be a list of words in the string but without any leading or trailing whitespace.
1. Using str.split() function
The Pythonic way of splitting on a string in Python uses the str.split(sep) function. It splits the string based on the specified delimiter sep. When the delimiter is not provided, the consecutive whitespace is treated as a separator.
This is demonstrated below, where the no-arg split function splits on whitespace:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "a b \t c \r\n d e" words = s.split() print(words) # ['a', 'b', 'c', 'd', 'e'] |
2. Using Regular Expression
This can also be done using regular expressions. However, regular expressions are not considered very Pythonic and would be overkill for such a trivial task. Here’s a Python program that demonstrates it:
|
1 2 3 4 5 6 7 8 |
import re if __name__ == '__main__': s = "a b \t c \r\n d e" words = re.split('\s+', s) print(words) # ['a', 'b', 'c', 'd', 'e'] |
That’s all about splitting a string on whitespace 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 :)