Skip to content

'in-place' string modifications in Python

stackoverflow.com
1 pointsea6ear1 comment
On HN

Comments

As pointed out, strings are immutable and depending on F(c) being mostly c or not, different approaches might work best.

Eg. for a single replacement (I haven't seen this one mentioned), slicing might work best: s[:i-1] + F(s[i]) + s[i+1:]. This is obviously good for a small number of replacements too, though you might want to switch to "".join(iterable) for better performance.

In general, immutability of strings requires a more functional approach than in-place editing.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.