How to Split a String on Whitespace in Python
When working with strings, you may encounter situations where you need to divide them into smaller segments based on specific delimiters. One common delimiter is whitespace, which includes spaces, tabs, and newlines.
In Python, the str.split() method provides an easy way to split a string into a list of substrings based on a specified delimiter. However, by default, the str.split() method doesn't split on whitespace automatically. To do so, you need to explicitly pass None as the argument:
>>> "many fancy word \nhello \thi".split() ['many', 'fancy', 'word', 'hello', 'hi']
By passing None as the argument, the str.split() method interprets any whitespace characters as delimiters and splits the string accordingly. This allows you to separate words, phrases, or tokens from a larger string.
The above is the detailed content of How do I Split a String on Whitespace in Python?. For more information, please follow other related articles on the PHP Chinese website!