Python Program to swap the First and the Last Character of a string

Python Program to swap the First and the Last Character of a string

Let's create a tutorial on how to swap the first and last character of a string in Python.

Objective: Given a string, swap its first and last characters.

Example:

Input String: "python" Output String: "nythop" 

Step-by-step Solution:

Step 1: Define the input string.

input_str = "python" 

Step 2: Define a function to swap the first and last characters of a string.

def swap_first_last(s): # If the string is empty or only contains a single character, return it as it is. if len(s) <= 1: return s # Get the first and last characters first_char = s[0] last_char = s[-1] # Swap the first and last characters and return the new string return last_char + s[1:-1] + first_char 

Step 3: Use the function to get the result.

result_str = swap_first_last(input_str) 

Step 4: Display the result.

print(result_str) 

Complete Program:

def swap_first_last(s): # If the string is empty or only contains a single character, return it as it is. if len(s) <= 1: return s # Get the first and last characters first_char = s[0] last_char = s[-1] # Swap the first and last characters and return the new string return last_char + s[1:-1] + first_char # Define the input string input_str = "python" # Get the string with swapped first and last characters result_str = swap_first_last(input_str) # Display the result print(result_str) 

Output:

nythop 

This tutorial provides a clear and efficient way to swap the first and last characters of a string in Python. The swap_first_last function is straightforward and handles edge cases where the string might be empty or contain only a single character.


More Tags

amazon-dynamodb lit-element least-squares browser-automation gtk azure-storage-files toastr mediawiki hyperlink twitter-bootstrap-4

More Programming Guides

Other Guides

More Programming Examples