Here, we will figure out how to swap characters of a given string utilizing python program?
Given a string, and we need to swap all characters utilizing python program.
In this article, we would figure out how to restore a string with swapped characters? This can be tackled by either presenting a variable N or by basically thinking about the length of the string itself.
Question:
In the event that you are given a string, return another string with the end goal that the first and the last characters have been traded. Likewise, you ought to think about the accompanying cases:
Example:
swap_string ('hate') = 'etah'
swap_string ('g') = 'g'
swap_string ('ca') = 'ac'
Code:
def swap_string(str):
if len(str) <= 1:
return str
mid = str[1:len(str) - 1]
return str[len(str) - 1] + mid + str[0]
print (swap_string('JustTechReview'))
print (swap_string('Work'))
print (swap_string('G'))
print (swap_string('I love dogs!'))
Output:
weiveRhceTtsuJ
kroW
G
!sgod evol I