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

How to Split a String on Whitespace in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 07:46:03699browse

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)

Output:

['many', 'fancy', 'word', 'hello', 'hi']

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)

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!

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