"a b c d e" +5 python regex whitespace David542 Jul 22 ...">

Collapse spaces

How can I collapse run spaces in python?

"a b   c   d      e" --> "a b c d e"
+5
source share
3 answers

Assuming

s = 'a b   c   d      e'

then

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

will give you the specified result.

This works with split () to split a string into a list of individual characters ['a', 'b', 'c', 'd', 'e']and then reattach them to the same space between them using the join () function in the string. split()also fulfills any leading or trailing spaces.

Simple-based is better than complex (Zen of Python) to avoid the regular expression " two problems " problem :)

+14
source

With regex (due to tag):

re.sub('\s+', ' ', "a b   c   d      e")
+5
source

, :

re.sub('\s+(?=\s)', '', str)

, , , :

re.sub('(?:^\s+|\s+(?=\s)|\s+$)', '', str)
0

All Articles