Reverse the fragment. Given a string in which the letter “h” occurs at least twice, reverse the sequence of characters enclosed between the first and last occurrences of “h”.
|
s = input() first_index = s.find('h') last_index = s.rfind('h') reversed_middle = s[first_index + 1:last_index][::-1] print(s[:first_index + 1] + reversed_middle + s[last_index:]) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user and stores it in the variable s
.
- Finding the First and Last Index of ‘h’:
first_index = s.find('h')
last_index = s.rfind('h')
- The
find('h')
method returns the index of the first occurrence of ‘h’.
- The
rfind('h')
method returns the index of the last occurrence of ‘h’.
- Reversing the Characters Between the First and Last ‘h’:
reversed_middle = s[first_index + 1:last_index][::-1]
s[first_index + 1:last_index]
extracts the substring between the first and last occurrences of ‘h’.
- The
[::-1]
slice reverses this substring.
- Constructing the Resulting String:
print(s[:first_index + 1] + reversed_middle + s[last_index:])
s[:first_index + 1]
gives the substring from the start up to and including the first ‘h’.
reversed_middle
is the reversed substring between the first and last ‘h’.
s[last_index:]
gives the substring from the last ‘h’ to the end.
- Concatenating these parts constructs the final string.