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.
CodePudding user response:
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..."
CodePudding user response:
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])])
CodePudding user response:
Here's my step-by-step solution:
- Split into list from
,
. - Append list and check for odd.
- 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)