简体   繁体   中英

How do you replace every occurrence of a letter in a string apart from the first and the last ones?

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.

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))

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:]

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM