Replace within the fragment. Given a string, replace every occurrence of the letter “h” with the letter “H”, except for the first and the last occurrences.
|
s = input() first_index = s.find('h') last_index = s.rfind('h') middle = s[first_index + 1:last_index].replace('h', 'H') print(s[:first_index + 1] + 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’.
- Replacing ‘h’ with ‘H’ in the Middle Part:
middle = s[first_index + 1:last_index].replace('h', 'H')
s[first_index + 1:last_index]
extracts the substring between the first and last occurrences of ‘h’.
- The
replace('h', 'H')
method replaces all occurrences of ‘h’ with ‘H’ in this substring.
- Constructing the Resulting String:
print(s[:first_index + 1] + middle + s[last_index:])
s[:first_index + 1]
gives the substring from the start up to and including the first ‘h’.
middle
is the modified substring with ‘h’ replaced by ‘H’.
s[last_index:]
gives the substring from the last ‘h’ to the end.
- Concatenating these parts constructs the final string.