Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
'in-place' string modifications in Python (stackoverflow.com)
1 point by sea6ear on Nov 13, 2023 | hide | past | favorite | 1 comment


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: