Python字符串替换,替换开头字符串,替换结尾字符串

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值