Search code examples
stringpython-2.7swap

Swap characters in string


I am new to python and I want to know how can I swap two characters in a string. I know string is immutable so I need to find a way to create a new string with the characters swapped. Specifically, a general method which takes a string and two indexes i,j and swaps the character on i with j.


Solution

  • As you correctly state, strings are immutable and can't be modified in-place - but we can create a new string with the swapped characters. Here's one idea: let's convert the string into a list, swap the elements in the list and then convert the list back into a string:

    def swap(s, i, j):
        lst = list(s)
        lst[i], lst[j] = lst[j], lst[i]
        return ''.join(lst)
    

    Another possible implementation would be to manipulate the string using slices and indexes:

    def swap(s, i, j):
        return ''.join((s[:i], s[j], s[i+1:j], s[i], s[j+1:]))
    

    Either way, it works as expected:

    swap('abcde', 1, 3)
    => 'adcbe'