Home >Backend Development >Python Tutorial >How to Split a String by Whitespace in Python?

How to Split a String by Whitespace in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 15:39:02997browse

How to Split a String by Whitespace in Python?

Whitespace Delimited Strings in Python

String handling is a common task in programming, and in Python, whitespace separated strings can be easily Split the string at.

Using Python's str.split() method, you can split a string into a list by spaces (whitespace characters):

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

The str.split() method defaults to whitespace Characters such as spaces, tabs, and newlines are delimiters. So the above code separates the input string into a list of words separated by whitespace characters.

It is worth noting that the str.split() method can also use a regular expression as a parameter to perform more refined segmentation. However, for simple whitespace separation, the default behavior is sufficient.

The above is the detailed content of How to Split a String by 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