Answers for "python swapping characters in string"

2

python swapping characters in string

def swap(string, i, j):
    """
    Swapping between 2 given indices of a chars in a string
    :param string: string
    :param i: first index
    :param j: second index
    :return: new string with the swapped chars
    """
    string = list(string)
    string[i], string[j] = string[j], string[i]
    return ''.join(string)

# EXAMPLE
str = "example"
print(swap(str, 0, 1)) # print "xeample"
Posted by: Guest on April-06-2021

Python Answers by Framework

Browse Popular Code Answers by Language