I've seen many questions on the most efficient way to do certain things, but one I haven't seen (and one which would help a lot) is the most efficient way to swap two characters in a string. As I thought of it, I immediately went to converting it into a list, swapping the elements, and then joining it back:
def swap(s: str, index1: int, index2: int) -> str:
new_s = list(s)
new_s[index1], new_s[index2] = new_s[index2], new_s[index1]
return "".join(new_s)
However, I was wondering if there's a better way. I tried list slicing with something like this:
def swap(s: str, index1: int, index2: int) -> str:
lindex = min(index1, index2)
gindex = max(index1, index2)
return s[:lindex] + s[gindex] + s[lindex + 1:gindex] + s[lindex] + s[gindex + 1:]
However, it seemed to be much slower, a whole 45% slower than the first approach. Does anyone of a better (read: more efficient) solution to this? Or is the most efficient way just converting it to a list?