heyang78

比如有个字符串http://www.55188.com/thread-8306254-2-3.html,需要把8306254后面的2替换成其它数字,其它保持不变,该如何办呢?请看代码:

import re

url=\'http://www.55188.com/thread-8306254-2-3.html\'
pattern=\'-(\d+)-(\d+)-(\d+)\'
i=5678
newUrl=re.sub(pattern,lambda m:\'-\'+m.group(1)+\'-\'+str(i)+\'-\'+m.group(3),url)
print(newUrl)

控制台输入如下:

C:\Users\horn1\Desktop\python\26>python sub.py
http://www.55188.com/thread-8306254-5678-3.html

Python的局部替换比JS/Nodejs的还是差点意思,后者直接用$1,$2,$3就可以了。

分类:

技术点:

相关文章:

  • 2021-12-24
  • 2022-02-13
  • 2021-11-07
  • 2022-01-12
  • 2021-11-20
  • 2021-09-22
  • 2021-07-03
  • 2021-12-24
猜你喜欢
  • 2021-12-24
  • 2021-12-24
  • 2021-12-16
  • 2021-12-24
  • 2022-02-09
  • 2021-09-30
相关资源
相似解决方案