Home >Backend Development >Python Tutorial >How do I split a string into substrings based on whitespace in Python?

How do I split a string into substrings based on whitespace in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 17:55:02344browse

How do I split a string into substrings based on whitespace in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn