How Do I Replace Multiple Spaces With Just One Character?
Solution 1:
This pattern will replace any groups of whitespace with a single underscore
newstring = '_'.join(input1.split())
If you only want to replace spaces (not tab/newline/linefeed etc.) it's probably easier to use a regex
importrenewstring= re.sub(' +', '_', input1)
Solution 2:
Dirty way:
newstring = '_'.join(input1.split())
Nicer way (more configurable):
importrenewstring= re.sub('\s+', '_', input1)
Extra Super Dirty way using the replace
function:
defreplace_and_shrink(t):
'''For when you absolutely, positively hate the normal ways to do this.'''
t = t.replace(' ', '_')
if'__'notin t:
return t
t = t.replace('__', '_')
return replace_and_shrink(t)
Solution 3:
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'
Post a Comment for "How Do I Replace Multiple Spaces With Just One Character?"