Replace character in python string every even or odd occurrence

Question:

I have the following python string:


strng='1.345 , 2.341 , 7.981 , 11.212 , 14.873 , 7.121...'

How can I remove all the ‘,’ that their occurrence is odd, to get the following string:

strng='1.345  2.341 , 7.981  11.212 , 14.873 7.121,...'

(Removed "," )

I know to use replace but to replace all specific characters and not only odd or double.

Asked By: Reut

||

Answers:

Here’s my step-by-step solution:

  1. Split into list from ,.
  2. Append list and check for odd.
  3. Simply update res
strng='1.345 , 2.341 , 7.981 , 11.212 , 14.873 , 7.121...'
newString = strng.split(',')
res = ""
for i in range(len(newString)):
    res+=newString[i]
    if i%2 != 0: res+=" , "
# Thanks to @areop-enap
# This code prevents trailing comma if you don't want.
if res[-2:-1] == ',': res = res[:-3] # checks if 2nd last string is and slices it
print(res)
Answered By: The Myth

A solution using list comprehension:

"".join ( [[",",""][i&1 if i else 1]+l for i, l in enumerate(strng.split(','))] )

The result of this piece of code is a string. Output:

"1.345  2.341 , 7.981  11.212 , 14.873  7.121..."
Answered By: areop-enap

A zip()-based solution.

Combines sublists made of pairs of items : one that starts from the beginning (index=0) and the second starting at the 2nd element (index=1).

items = strng.replace(",", "").split()
strng = " , ".join([f"{x} {y}" for x, y in zip(items[::2],items[1::2])])
Answered By: 0x0fba
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.