Exchange characters in a string

I am new to python and I want to know how I can change two characters in a string. I know that a string is immutable, so I need to find a way to create a new string with replaced characters. In particular, a general method that takes a string and two indices i, j and swaps a character onto i with j.

+6
source share
1 answer

As you correctly state, the lines are immutable and cannot be changed in place, but we can create a new line with replaced characters. Here is one idea: let's convert a string to a list, swap elements in a list, and then convert the list back to string:

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

Another possible implementation is 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:])) 

In any case, it works as expected:

 swap('abcde', 1, 3) => 'adcbe' 
+13
source

Source: https://habr.com/ru/post/975595/


All Articles