Home » Python » Python programs

Python program to swap characters of a given string

Here, we are going to learn how to swap characters of a given string using python program?
Submitted by Suryaveer Singh, on June 08, 2019

Given a string, and we have to swap all characters using python program.

In this article, we would learn how to return a string with swapped characters? This can be solved by either introducing a variable N or by just simply considering the length of the string itself.

Question:

If you are provided with a string, return a new string such that the first and the last characters have been exchanged. Also, you should consider the following cases:

Example:

    swap_string ('love') = 'eovl'
    swap_string ('g') = 'g'
    swap_string ('ab') = 'ba'

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('IncludeHelp'))
print (swap_string('Hello'))
print (swap_string('G'))
print (swap_string('I love my India!'))

Output

pncludeHelI
oellH
G
! love my IndiaI





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.