How to replace multiple spaces with one character?

Here is my code:

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

So, if I put my input as:

I want only    one     underscore.

Currently it displays as:

I_want_only_____one______underscore.

But I want it to look like this:

I_want_only_one_underscore.
+5
source share
3 answers

This template will replace any space group with a single underscore

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

If you want to replace spaces (not tab / newline / linefeed etc.), it might be easier to use a regex

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

Dirty way:

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

More convenient way (more customizable):

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

Extra super dirty way using the function 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)
+6
source

( )

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

()

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

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

All Articles