0

How do I reduce whitespace in Python from

test = ' Good ' to single whitespace test = ' Good '

I have tried define this function but when I try to test = reducing_white(test) it doesn't work at all, does it have to do with the function return or something?

counter = []

def reducing_white(txt):
    counter = txt.count(' ')
    while counter > 2: 
      txt = txt.replace(' ','',1)
      counter = txt.count(' ')
      return txt
Ralph Deint
  • 380
  • 1
  • 4
  • 15
  • 4
    Duplicate of http://stackoverflow.com/questions/2077897/substitute-multiple-whitespace-with-single-whitespace-in-python or http://stackoverflow.com/questions/1546226/a-simple-way-to-remove-multiple-spaces-in-a-string-in-python? – alecxe Apr 28 '16 at 02:38
  • You call `return` in the very first iteration of your loop. Maybe you meant to place that `return` outside of your loop? – larsks Apr 28 '16 at 02:38
  • The code doesn't really make much sense. For one thing, it's not making any distinction between consecutive spaces vs. isolated spaces. – Tom Karzes Apr 28 '16 at 02:40
  • @alecxe: I'm curious. You have the gold python badge, so why not close as a duplicate? The answers that are here aren't improving on the answers there ... – zondo Apr 28 '16 at 02:45
  • @zondo decided to play it safely, wait for the OP to respond or make the problem different. But, you are right, closing. Thanks. – alecxe Apr 28 '16 at 02:46
  • @alecxe sorry for the question, I am new to python. Thank you for the help. – Ralph Deint Apr 28 '16 at 03:47

2 Answers2

0

Here is how I solved it:

def reduce_ws(txt):
    ntxt = txt.strip()
    return ' '+ ntxt + ' '

j = '    Hello World     '
print(reduce_ws(j))

OUTPUT:

' Hello World '

0

You need to use regular expressions:

import re

re.sub(r'\s+', ' ', test)
>>>> ' Good '

test = '     Good    Sh ow     '
re.sub(r'\s+', ' ', test)
>>>> ' Good Sh ow '

r'\s+' matches all multiple whitespace characters, and replaces the entire sequence with a ' ' i.e. a single whitespace character.

This solution is fairly powerful and will work on any combination of multiple spaces.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44