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

How to Split a String on Whitespace in Python?

Susan Sarandon
Release: 2024-11-10 07:46:03
Original
768 people have browsed it

How to Split a String on Whitespace in Python?

Split String on Whitespace in Python (Duplicate)

You can split a string on whitespace in Python using the str.split() method without specifying an argument. This method assumes that the input string should be split on all whitespace characters, including spaces, newlines, and tabs.

Consider the following example:

str = "many   fancy word \nhello    \thi"
words = str.split()
print(words)
Copy after login
Copy after login

Output:

['many', 'fancy', 'word', 'hello', 'hi']
Copy after login

The str.split() method has split the input string on all whitespace characters, resulting in a list of words. This method is similar to the Java method str.split(String regex), where the regex argument specifies the regular expression that defines the split points. By omitting the regex argument, you use the default regular expression that matches all whitespace characters.

Therefore, to achieve the same result as the Java code provided in the question, simply use the following Python code:

str = "many   fancy word \nhello    \thi"
words = str.split()
print(words)
Copy after login
Copy after login

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