【问题标题】:How do you replace every occurrence of a letter in a string apart from the first and the last ones?除了第一个和最后一个之外,如何替换字符串中每个出现的字母?
【发布时间】:2017-08-31 16:03:29
【问题描述】:

我正在使用 .replace 方法将小写 h 替换为大写 h,但我不想替换 h 的第一次和最后一次出现。这是我目前所拥有的:

string = input()
print(string.replace('h', 'H', ?))

我不确定将什么作为 .replace 函数的最后一个参数。 提前致谢。

【问题讨论】:

    标签: python string input replace printing


    【解决方案1】:

    试试这个:

    string = input()
    substring = string[string.find('h') + 1:]
    print(string[:string.find('h') + 1] + substring.replace('h', 'H', substring.count('h') - 1))
    

    【讨论】:

      【解决方案2】:

      你可以找到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:]
      

      【讨论】:

        【解决方案3】:

        您可以将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
        

        【讨论】:

          【解决方案4】:

          试试这个:

          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)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-13
            • 2013-06-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多