Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse run-on whitespace

How would I collapse run-on whitespace in python?

"a b   c   d      e" --> "a b c d e"
like image 927
David542 Avatar asked Jul 22 '12 19:07

David542


1 Answers

Assuming

s = 'a b   c   d      e'

then

' '.join(s.split())
'a b c d e'

will give you the specified output.

This works by using split() to break the string into into a list of individual characters ['a', 'b', 'c', 'd', 'e'] and then joining them again with a single space in-between using the join() function into a string. The split() also takes care of any leading or trailing blanks.

Based on Simple is better than complex (Zen of Python) in order to avoid the regex "two problem" problem :)

like image 78
Levon Avatar answered Oct 01 '22 19:10

Levon