【发布时间】:2017-08-31 16:03:29
【问题描述】:
我正在使用 .replace 方法将小写 h 替换为大写 h,但我不想替换 h 的第一次和最后一次出现。这是我目前所拥有的:
string = input()
print(string.replace('h', 'H', ?))
我不确定将什么作为 .replace 函数的最后一个参数。 提前致谢。
【问题讨论】:
标签: python string input replace printing
我正在使用 .replace 方法将小写 h 替换为大写 h,但我不想替换 h 的第一次和最后一次出现。这是我目前所拥有的:
string = input()
print(string.replace('h', 'H', ?))
我不确定将什么作为 .replace 函数的最后一个参数。 提前致谢。
【问题讨论】:
标签: python string input replace printing
试试这个:
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:]
【讨论】:
您可以将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
【讨论】:
试试这个:
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)
【讨论】: