Reputation: 205
I'm using the .replace method to replace lower case h's with upper case h's, but i do not want to replace the first and last occurrences of h's.. this is what i have so far:
string = input()
print(string.replace('h', 'H', ?))
I'm not sure what to put as the last argument in the .replace function. Thanks in advance.
Upvotes: 0
Views: 1752
Reputation: 2159
Try This one:
st=input()
i=st.index('h')
j=len(st)-1-st[::-1].index('h')
st=st[:i+1]+st[i+1:j].replace("h","H")+st[j:]
print (st)
Upvotes: 0
Reputation: 91498
You could use pattern.sub
with a callback, the following replaces all h
by H
when they are between 2 h
's
mystring = 'I say hello hello hello hello hello'
pat = re.compile(r'(?<=h)(.+)(?=h)')
res = pat.sub(lambda m: m.group(1).replace(r'h', 'H') , mystring)
print res
Output:
I say hello Hello Hello Hello hello
Upvotes: 0
Reputation: 2265
You can find first and last position of h
and replace in splice of string
string = input()
lindex = string.find('h')
rindex = string.rfind('h')
buf_string = string[lindex + 1:rindex]
buf_string.replace('h', 'H')
string = string[:lindex + 1] + buf_string + string[rindex:]
Upvotes: 1
Reputation: 1120
Try this one:
string = input()
substring = string[string.find('h') + 1:]
print(string[:string.find('h') + 1] + substring.replace('h', 'H', substring.count('h') - 1))
Upvotes: 1