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

ajk*_*y94 7 python python-3.x

到目前为止,这是我的代码:

input1 = input("Please enter a string: ")
newstring = input1.replace(' ','_')
print(newstring)
Run Code Online (Sandbox Code Playgroud)

所以,如果我输入我的输入:

I want only    one     underscore.
Run Code Online (Sandbox Code Playgroud)

它目前显示为:

I_want_only_____one______underscore.
Run Code Online (Sandbox Code Playgroud)

但我想让它像这样出现:

I_want_only_one_underscore.
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 27

此模式将使用单个下划线替换任何空白组

newstring = '_'.join(input1.split())
Run Code Online (Sandbox Code Playgroud)

如果你只想更换空格(不是tab /换行/换行等),那么使用正则表达式可能更容易

import re
newstring = re.sub(' +', '_', input1)
Run Code Online (Sandbox Code Playgroud)


Hen*_*ter 6

脏的方式:

newstring = '_'.join(input1.split())
Run Code Online (Sandbox Code Playgroud)

更好的方式(更可配置):

import re
newstring = re.sub('\s+', '_', input1)
Run Code Online (Sandbox Code Playgroud)

使用该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)
Run Code Online (Sandbox Code Playgroud)


fun*_*unk 5

第一种方法(不起作用)

>>> a = '213         45435             fdgdu'
>>> a
'213         45435                            fdgdu                              '
>>> b = ' '.join( a.split() )
>>> b
'213 45435 fdgdu'
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,变量 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 :( )
Run Code Online (Sandbox Code Playgroud)

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

第二种方法(有效)

>>> 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'
Run Code Online (Sandbox Code Playgroud)

第三种方法(有效)

在我看来,这种方法有点Pythonic。核实:

>>> a = '213\n         45435\n             fdgdu\n '
>>> b = ' '.join( filter( len, a.split( ' ' ) ) )
>>> b
'213\n 45435\n fdgdu\n'
Run Code Online (Sandbox Code Playgroud)