Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on whitespace in Python [duplicate]

I'm looking for the Python equivalent of

String str = "many   fancy word \nhello    \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex);  ["many", "fancy", "word", "hello", "hi"] 
like image 752
siamii Avatar asked Nov 13 '11 18:11

siamii


People also ask

How do you split a string in whitespace in Python?

The Pythonic way of splitting on a string in Python uses the str. split(sep) function. It splits the string based on the specified delimiter sep . When the delimiter is not provided, the consecutive whitespace is treated as a separator.

How do you split with whitespace?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.


1 Answers

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split() ['many', 'fancy', 'word', 'hello', 'hi'] 
like image 78
Sven Marnach Avatar answered Oct 22 '22 22:10

Sven Marnach