sKen
sKen

Reputation: 105

Python replace every odd occurrence of space with "_"

I have the following string where I should replace every odd occurrence of space `` with _.

String:

901 R 902 M 903 Picture_message 904 NA 905 F 906 Local_Relay 907 46 908 51705 909 306910001112/[email protected]

Expected String:

901_R 902_M 903_Picture_message 904_NA 905_F 906_Local_Relay 907_46 908_51705 909_306910001112/[email protected]

Upvotes: 1

Views: 1707

Answers (3)

Blckknght
Blckknght

Reputation: 104752

You can use a regex to handle this. You need to match a space, followed by any non-space characters, followed by another space or the end of the input. You replace the first space, but not the second one.

re.sub(r' ([^ ]*(?: |$))', r'_\1', text)

Upvotes: 5

Martijn Pieters
Martijn Pieters

Reputation: 1123850

You could use a regular expression with a replacement function that only actually replaces every odd call:

from itertools import count
import re

def replace_odd_spaces(text):
    counter = count()
    return re.sub('\s+', lambda m: match.group() if next(counter) % 2 else '_', text)

Demo:

>>> text = '901 R 902 M 903 Picture_message 904 NA 905 F 906 Local_Relay 907 46 908 51705 909 306910001112/[email protected]'
>>> replace_odd_spaces(text)
'901_R 902_M 903_Picture_message 904_NA 905_F 906_Local_Relay 907_46 908_51705 909_306910001112/[email protected]'

Upvotes: 0

mgilson
mgilson

Reputation: 310089

First, I'd probably split the string into it's constituent parts:

pieces = s.split()

Then I'd join the every element and it's appropriate neighbor with _ and join the rest with ' '...

' '.join('_'.join(pieces[i:i+2]) for i in xrange(0, len(pieces), 2))

Demo:

>>> s = '901 R 902 M 903 Picture_message 904 NA 905 F 906 Local_Relay 907 46 908 51705 909 306910001112/[email protected]'
>>> pieces = s.split()
>>> ' '.join('_'.join(pieces[i:i+2]) for i in xrange(0, len(pieces), 2))
'901_R 902_M 903_Picture_message 904_NA 905_F 906_Local_Relay 907_46 908_51705 909_306910001112/[email protected]'

Upvotes: 1

Related Questions