Python 除了第一个和最后一个字母外,如何替换字符串中出现的每个字母?

Python 除了第一个和最后一个字母外,如何替换字符串中出现的每个字母?,python,string,input,replace,printing,Python,String,Input,Replace,Printing,我正在使用.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] + s

我正在使用.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))
试试这个:

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

您可以找到
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)
试试这个:

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
位于2
h
之间时,以下命令将它们替换为
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

您可以将
pattern.sub
与回调一起使用,当所有
h
位于2
h
之间时,以下命令将它们替换为
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