Splitting Strings on Whitespace in Python
In Python, you can split a string into multiple substrings based on a specified delimiter. When dealing with whitespace specifically, a common approach is to use the str.split() method without providing an argument:
my_string = "many fancy word \nhello \thi" result = my_string.split()
This operation automatically splits the string into substrings based on whitespace characters, including spaces, tabs, and newlines. The result would be:
result = ['many', 'fancy', 'word', 'hello', 'hi']
This approach is convenient and efficient for splitting strings on whitespace, as it doesn't require specifying a specific regular expression pattern. However, it's important to note that it will split the string on any consecutive whitespace characters, and consecutive spaces are treated as a single delimiter.
The above is the detailed content of How do I split a string into substrings based on whitespace in Python?. For more information, please follow other related articles on the PHP Chinese website!