Python字符串替换,替换开头字符串,替换结尾字符串
创始人
2025-05-29 22:48:19

import re

srcs = "hello 123, world, 456"
print(srcs)
pat = r'\d+'
dests = re.compile(pat).sub('888', srcs) //第一个参数根据正则表达式替换原始字符串
print(dests)

eliminate = re.compile('\d+')
text = eliminate.sub("888", "hello 123, world, 456")
print(text)

输出

hello 123, world, 456

hello 888, world, 888

hello 888, world, 888

替换结尾字符串:

servicename = re.sub('Interface' + '$', '', 'Interface_InterfaceserviceInterfaceInterface_Interface')

print(servicename)
//'$' 表示结尾,所以会替换结尾处的字符串

输出:

Interface_InterfaceserviceInterfaceInterface_

替换开头的字符串:

servicename = re.sub('^'+'Interface', '', 'Interface_InterfaceserviceInterfaceInterface_Interface')
print(servicename)
//'^' 表示开头,所以会替换开头处的字符串

servicename = 'Interface_InterfaceserviceInterfaceInterface_Interface'.replace('Interface', '', 1)
print(servicename)

// 后面这个1表示替换次数,1次就替换最开始匹配的字符串

输出:

_InterfaceserviceInterfaceInterface_Interface

_InterfaceserviceInterfaceInterface_Interface

相关内容

热门资讯

被掌上工美APP的贵金属订购交...   期货投资是一件风险极高的事情,不少投资者根本就没有做过期货交易,而掌上工美APP就是一款做贵金属...
天天铂银APP、天天白银APP...   天天铂银APP、天天白银APP及其背后华通系的交易软件,都存在虚假宣传,诱导投资者的行为!天天铂...
伊朗:特朗普“极度渴望”达成协... 央视新闻消息,伊朗伊斯兰议会议长卡利巴夫17日在社交媒体发文称,霍尔木兹海峡的控制权属于伊朗,这一事...
伊朗:特朗普7项社媒声明“均不... 新华社消息,伊朗伊斯兰议会议长卡利巴夫18日凌晨在社交媒体发文称, 美国总统特朗普此前在1小时内于社...
特朗普称将很快发布第一批UFO... △美国总统特朗普(资料图) 美国总统特朗普17日在一场集会活动上表示,他领导的政府找到了许多关于不明...