【问题标题】:How to replace the next three characters?如何替换接下来的三个字符?
【发布时间】:2019-03-16 14:35:42
【问题描述】:

如果模式中有字符“ai”或“hi”,则将接下来的三个字符替换为 * \ *

string = """
Or help one fainting robin
Unto his nest again,
I shall not live in vain
"""

输出应该是:

或者帮助一个fai*\*ng robin
再次嗨*\*est,
我不会白活。

【问题讨论】:

  • 你试过什么?你遇到了什么问题?
  • 欢迎来到 Stack Overflow!请熟悉这些常见问题并重新发布您的问题 - (1) 如何创建一个最小、完整和可验证的示例 - stackoverflow.com/help/mcve 和 (2) 为什么投票很重要? -stackoverflow.com/help/why-vote。 -- 快乐编码!
  • 感谢您的及时回复。我想出了替换部分,但无法继续使用下一个字符。 @TkTech

标签: python python-3.x string replace


【解决方案1】:

使用re.sub:

re.sub(r"([ah]i).{3}", r"\1*/*", string)

【讨论】:

    【解决方案2】:

    试试

    import re
    
    strings_to_find = ['ai', 'hi']
    
    data = 'Or help one fainting robin Unto his nest again'
    for string_to_find in strings_to_find:
        offsets = [m.start() for m in re.finditer(string_to_find, data)]
        for offset in offsets:
            data = data[:offset + len(string_to_find)] + '*\*' + data[offset + len(string_to_find) + 3:]
    print(data)
    

    【讨论】:

      【解决方案3】:

      您需要检查当前字符是“a”,下一个是“i”还是其他选项(“h”和“i”)。

      让我们做一些代码:

      string = "Or help one fainting robin Unto his nest again, I shall not live in vain"
      string_new = string.split()
      
      >>> string_new
      ['Or', 'help', 'one', 'fainting', 'robin', 'Unto', 'his', 'nest', 'again,', 'I', 'shall', 'not', 'live', 'in', 'vain']
      
      for phrase in string_new:
          for i in range(len(phrase)):
              if (phrase[i] == "a" and phrase[i+1] == "i") or (phrase[i] == "h" and phrase[i+1] == "i"):
                  print(phrase)
      

      我将字符串拆分为一个新字符串(将空格删除为一个字符串,另一个是字符串向量)。

      接下来,我将使用第一个 for 逐个字符串运行向量。对于第二个,我正在逐个字符地运行整个字符串。然后我做一些检查来确定我的字符串是否有“ai”或“hi”。如果字符串包含其中一些字符,我会打印它们。

      现在,您只需将相应的字符更改为您想要的字符

      【讨论】:

        猜你喜欢
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 2020-07-16
        • 2013-01-07
        相关资源
        最近更新 更多