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.
SQL Server REPLACE() Function The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With