Python Program to Swap Two Character of Given String

Through this python tutorial, we would like to share with you how to swap first and last characters of given string in python.

Python Program to Swap Two Character of Given String

There are two python programs available in this tutorial for how to swap two characters in a string python; as follows:

  • 1: Python swap first and last character of string
  • 2: Python swap characters of the string

1: Python swap first and last character of string

  • Define a function, which is used to swap characters of given string.
  • Allow user to input a string.
  • Call swap() with [ass the string as an argument to a function.
  • Print result.
# swap characters in string
def swap(str):
    if len(str) <= 1:
        return str

    mid = str[1:len(str) - 1]
    return str[len(str) - 1] + mid + str[0]

# take string from user
str1 = input("Please Enter String : ")

print (swap(str1))

After executing the program, the output will be:

Please Enter String :  hello
oellh

2: Python swap characters of the string

  • Define function, which is used to swap a string characters.
  • Allow user to input a string and store it in a variable.
  • Call function with Pass the string as an argument to a function.
  • Print the result
# swap characters in string
def swap(string):
      return string[-1:] + string[1:-1] + string[:1]

# take string from user
str1 = input("Please Enter String : ")

print (swap(str1))

After executing the program, the output will be:

Please Enter String :  dev
ved

Recommended Python Programs

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Python Program to Swap Two Character of Given String

  1. how do you swap the first 2 characters then swap the 3rd and 4th characters and then the next two and so on in python…

Leave a Reply

Your email address will not be published. Required fields are marked *