Python Question

Why does this :

a = ",,,,"
print(a.replace(",,",",0,"))

produce this :
,0,,0,

instead of this :
,0,0,0,

?

Looks like replace generates a new string based on processing the original, rather than replacing in-place. So the first two commas generate the new string β€œ,0,” and are then skipped, then the second two commas add in another set for β€œ,0,0,”.

I’d expect to see your second option only if it were replacing in the string itself. But Python strings are immutable, so it can’t do that.

1 Like

Sometimes you can’t see the wood for the trees.

Thanks.