2016-04-28 12 views
0

はどのように私は、この関数を定義するが、私はtest = reducing_white(test)しようとすると、それがすべてでは動作しません試してみましたtest = ' Good 'Pythonの空白を減らすには?

単一の空白に

test = ' Good 'からPythonで空白を減らすやる、それが関連していません関数の戻り値か何か?ここで

counter = [] 

def reducing_white(txt): 
    counter = txt.count(' ') 
    while counter > 2: 
     txt = txt.replace(' ','',1) 
     counter = txt.count(' ') 
     return txt 
+4

重複したhttp://stackoverflow.com/questions/2077897/substitute-multiple-whitespace-with-single-whitespace-in-pythonまたはhttp://stackoverflow.com/questions/1546226/a-simple-way -to-multiple-spaces-in-a-string-in-python? – alecxe

+0

ループの最初の繰り返しで 'return'を呼び出します。ループの外側に 'return'を置くつもりだったのでしょうか? – larsks

+0

コードはあまり意味をなさない。一つは、連続したスペースと孤立したスペースを区別しないことです。 –

答えて

0

は、私はそれを解決する方法である:

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

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

OUTPUT:

'Hello Worldの' あなたは、正規表現を使用する必要があります

0

import re 

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

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

をはすべての複数の空白文字に一致し、シーケンス全体を' '、つまり単一の空白文字に置き換えます。

このソリューションはかなり強力で、複数のスペースを組み合わせて使用​​できます。

関連する問題