11

これまでの私のコードは次のとおりです。

input1 = input("Please enter a string: ")
newstring = input1.replace(' ','_')
print(newstring)

したがって、入力を次のように入力すると:

I want only    one     underscore.

現在、次のように表示されます。

I_want_only_____one______underscore.

しかし、私はそれを次のように表示したい:

I_want_only_one_underscore.
4

3 に答える 3

31

このパターンは、空白のグループを単一のアンダースコアに置き換えます

newstring = '_'.join(input1.split())

スペースのみを置き換えたい場合 (タブ/改行/改行などではなく)、おそらく正規表現を使用する方が簡単です

import re
newstring = re.sub(' +', '_', input1)
于 2013-03-07T00:05:29.313 に答える
6

汚い方法:

newstring = '_'.join(input1.split())

より良い方法(より設定可能):

import re
newstring = re.sub('\s+', '_', input1)

関数を使用した超超汚い方法replace

def replace_and_shrink(t):
    '''For when you absolutely, positively hate the normal ways to do this.'''
    t = t.replace(' ', '_')
    if '__' not in t:
        return t
    t = t.replace('__', '_')
    return replace_and_shrink(t)
于 2013-03-07T00:08:08.107 に答える