def swap_first_last_char(string):
if len(string) <= 1:
return string
swapped_string = string[-1] + string[1:-1] + string[0]
return swapped_string
user_input = input("Enter a string: ")
result = swap_first_last_char(user_input)
print(f"String after swapping the first and last characters: {result}")
#source code --> clcoding.com
Code Explanation:
1. The swap_first_last_char Function
def swap_first_last_char(string):
This line defines a function named swap_first_last_char, which takes a single argument, string. This function is intended to swap the first and last characters of the string.
if len(string) <= 1:
return string
Condition Check: This checks if the length of the string is 1 or less.
If the string has 1 character (e.g., "a") or no characters at all (empty string ""), swapping the first and last characters wouldn't change anything.
So, in this case, it returns the original string as it is.
swapped_string = string[-1] + string[1:-1] + string[0]
Swapping Logic:
string[-1]: This accesses the last character of the string.
string[1:-1]: This accesses the middle part of the string (from the second character to the second-last character).
string[0]: This accesses the first character of the string.
The expression:
string[-1] + string[1:-1] + string[0]
Concatenates (combines) the last character, the middle part, and the first character in that order, effectively swapping the first and last characters.
return swapped_string
After swapping the characters, this line returns the new string that has the first and last characters swapped.
2. Taking User Input
user_input = input("Enter a string: ")
This line prompts the user to input a string.
The user's input is stored in the variable user_input.
3. Calling the Function and Displaying the Result
result = swap_first_last_char(user_input)
This line calls the function swap_first_last_char with the user_input as the argument. It stores the result (the swapped string) in the variable result.
print(f"String after swapping the first and last characters: {result}")
This line prints the result (the string with the first and last characters swapped) to the console using f-string formatting.
0 Comments:
Post a Comment