gpt4 book ai didi

python - 替换第二次出现的点的正则表达式

转载 作者:行者123 更新时间:2023-12-04 01:03:00 25 4
gpt4 key购买 nike

字符串是 Hello.world.hello。我想用“_”替换第二次出现的点。

str = "Hello. world. Hello!" 
x = re.sub(r'^((.){1}).', r'\1_', str)
#x = str.find(str.find('.')
print(x)
我得到的输出是'H_llo。世界。你好!'。正确的解决方法应该是什么

最佳答案

您可以使用

import re
text = "Hello. world. Hello!"
print( re.sub(r'^([^.]*\.[^.]*)\.', r'\1_', text) )
# => Hello. world_ Hello!
the Python demoregex demo .
细节:
  • ^ - 字符串开头
  • ([^.]*\.[^.]*) - 第 1 组:除 . 之外的任何零个或多个字符, 一个点和任何 0+ 非点
  • \. - 一个点。

  • 替换为第 1 组值 + _ .
    也可以不使用正则表达式:
    text = "Hello. world. Hello!" 
    chunks = text.split('.', 2) # split the text twice
    if len(chunks) > 2: # if there are more than 2 items
    print( fr'{".".join(chunks[0:2])}_{chunks[2]}' )
    else:
    print(text) # Replace the second dot or print the original
    # => Hello. world_ Hello!
    Python demo .

    关于python - 替换第二次出现的点的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67556502/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com