我使用.replace方法替换小写的h与大写H的,但我不想代替H公司的第一个和最后一个出现..这是我到目前为止有:除了第一个和最后一个字符串之外,如何替换字符串中每个字母的出现?
string = input()
print(string.replace('h', 'H', ?))
我不确定将什么作为.replace函数中的最后一个参数。 在此先感谢。
我使用.replace方法替换小写的h与大写H的,但我不想代替H公司的第一个和最后一个出现..这是我到目前为止有:除了第一个和最后一个字符串之外,如何替换字符串中每个字母的出现?
string = input()
print(string.replace('h', 'H', ?))
我不确定将什么作为.replace函数中的最后一个参数。 在此先感谢。
试试这个:
string = input()
substring = string[string.find('h') + 1:]
print(string[:string.find('h') + 1] + substring.replace('h', 'H', substring.count('h') - 1))
你可以找到h
第一和最后的位置和字符串拼接代替
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:]
试试这个:
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)
你可以使用pattern.sub
进行回调,以下内容替换全部h
通过H
当它们是2之间h
的
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
输出:
I say hello Hello Hello Hello hello