Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Without regex reduce multiple spaces in a string to one in Python

While answering this question I had a doubt regarding how to reduce multiple spaces in a string to one in Python without using regex. Say the string is as follows:

s = "Mary    had    a little lamb"

The first solution that came to my mind was

' '.join(s.split())

But this will not conserve leading and trailing spaces if the string was something like

s = "    Mary    had    a little lamb  "

In order to conserve leading and trailing spaces (if present), I came up with a slightly different approach where I added a dummy character to the starting and ending of the string (in this case a '-') which I later removed after the split. The code is as follows:

' '.join(('-' + s + '-').split())[1:-1]

Is there any other built in function or another pythonic way to do this?

Edit: By conserving leading and trailing spaces, I meant that in case there are multiple spaces at the beginning and/or at the end of the string, these multiple spaces should also be reduced to a single space

like image 779
Pulimon Avatar asked Oct 20 '22 17:10

Pulimon


1 Answers

You could use something like:

from itertools import groupby

s = "    Mary    had    a little lamb  "
res = ''.join(' ' if is_space else ''.join(chars) for is_space, chars in groupby(s, str.isspace))
#  Mary had a little lamb 
like image 183
Jon Clements Avatar answered Oct 23 '22 11:10

Jon Clements