Exercise 76

Develop a Python algorithm that transforms a given string, 's,' by exchanging its second character (s[1]) with the second-to-last character. It is assumed that the length of 's' is greater than or equal to 4. For instance, if 's' is 'Python', the algorithm should return the string 'Pothyn'."

Solution

def swap_characters(s):
    if len(s) >= 4:
        # Convert the string to a list for easy swapping
        s_list = list(s)
        
        # Swap the second character with the second-to-last character
        s_list[1], s_list[-2] = s_list[-2], s_list[1]
        
        # Convert the list back to a string
        result = ''.join(s_list)
        
        return result
    else:
        return "Input string should have a length greater than or equal to 4."

# Example usage
s = "Python"
result = swap_characters(s)
print(result)
# output : 'Pothyn'




 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 76 : Transform a given string by swapping its characters”

Leave a Reply