Home > Backend Development > Python Tutorial > How do I Split a String on Whitespace in Python?

How do I Split a String on Whitespace in Python?

Susan Sarandon
Release: 2024-11-09 22:19:02
Original
766 people have browsed it

How do I Split a String on Whitespace in Python?

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

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!

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