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

Barbara Streisand
Release: 2024-11-17 17:55:02
Original
249 people have browsed it

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()
Copy after login

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']
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template