Remove the fragment. Given a string in which the letter “h” occurs at least twice, remove the first and last occurrence of the letter “h”, as well as all characters between them.
|
s = input() first_index = s.find('h') last_index = s.rfind('h') print(s[:first_index] + s[last_index + 1:]) |
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’.
- Removing Characters Between the First and Last ‘h’:
print(s[:first_index] + s[last_index + 1:])
s[:first_index]
gives the substring from the start to just before the first ‘h’.
s[last_index + 1:]
gives the substring from just after the last ‘h’ to the end.
- Concatenating these two substrings results in the string with the first and last ‘h’ and all characters between them removed.