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

2024-05-15 00:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前的代码:

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.

Tags: 代码onlyinputstringonereplaceprintenter
3条回答

第一种方法(不起作用)

>>> 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'

肮脏的方式:

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)

此模式将用一个下划线替换任意一组空白

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

如果只想替换空格(而不是tab/newline/linefeed等),那么使用regex可能更容易

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

相关问题 更多 >

    热门问题