How do I replace multiple spaces with just one character?

后端 未结 3 834
孤独总比滥情好
孤独总比滥情好 2020-12-31 18:31

Here\'s my code so far:

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

So if I put in

3条回答
  •  [愿得一人]
    2020-12-31 19:20

    First approach (doesn't work)

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

    As you can see the variable a contains a lot of spaces between the "useful" sub-strings. The combination of the split() function without arguments and the join() function cleans up the initial string from the multiple white spaces.

    The previous technique fails when the initial string contains special characters such as '\n':

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

    In order to correct this we can use the following (more complex) solution.

    Second approach (works)

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

    Third approach (works)

    This approach is a little bit more pythonic in my eyes. Check it:

    >>> a = '213\n         45435\n             fdgdu\n '
    >>> b = ' '.join( filter( len, a.split( ' ' ) ) )
    >>> b
    '213\n 45435\n fdgdu\n'
    

提交回复
热议问题