如何用一个字符替换多个空格?

12 投票
3 回答
20282 浏览
提问于 2025-04-17 18:12

这是我目前的代码:

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.

3 个回答

5

第一种方法(不管用)

>>> a = '213         45435             fdgdu'
>>> a
'213         45435                            fdgdu                              '
>>> b = ' '.join( a.split() )
>>> b
'213 45435 fdgdu'

如你所见,变量 a 里面有很多“有用”的子字符串之间夹着很多空格。使用 split() 函数(不带参数)和 join() 函数的组合,可以把初始字符串中的多余空格清理掉。

不过,这种方法在初始字符串中包含特殊字符,比如 '\n' 时就不管用了:

>>> a = '213\n         45435\n             fdgdu\n '
>>> b = ' '.join( a.split() )
>>> b
'213 45435 fdgdu'   (the new line characters have been lost :( )

为了修正这个问题,我们可以使用以下(更复杂的)解决方案。

第二种方法(有效)

>>> a = '213\n         45435\n             fdgdu\n '
>>> tmp = a.split( ' ' )
>>> tmp
['213\n', '', '', '', '', '', '', '', '', '45435\n', '', '', '', '', '', '', '', '', '', '', '', '', 'fdgdu\n', '']
>>> while '' in tmp: tmp.remove( '' )
... 
>>> tmp
['213\n', '45435\n', 'fdgdu\n']
>>> b = ' '.join( tmp )
>>> b
'213\n 45435\n fdgdu\n'

第三种方法(有效)

在我看来,这种方法更符合 Python 的风格。来看看:

>>> a = '213\n         45435\n             fdgdu\n '
>>> b = ' '.join( filter( len, a.split( ' ' ) ) )
>>> b
'213\n 45435\n fdgdu\n'
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)
33

这个模式会把连续的空白字符替换成一个下划线。

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

如果你只想替换空格(不包括制表符、换行符等),那么使用正则表达式可能会更简单。

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

撰写回答