Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
Wajahat Avatar asked Sep 21 '14 00:09

Wajahat


People also ask

How do I swap characters in SQL?

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.


1 Answers

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'
like image 65
Óscar López Avatar answered Dec 21 '22 23:12

Óscar López