加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中扩展字符串中的所有出现

发布时间:2020-12-20 11:21:25 所属栏目:Python 来源:网络整理
导读:目标是在源字符串中为所有出现的子字符串(不区分大小写)添加前缀和后缀.我基本上需要弄清楚如何从source_str到target_str. source_str = 'You ARe probably familiaR with wildcard'target_str = 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[
目标是在源字符串中为所有出现的子字符串(不区分大小写)添加前缀和后缀.我基本上需要弄清楚如何从source_str到target_str.

source_str = 'You ARe probably familiaR with wildcard'
target_str = 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'

在这个例子中,我发现所有出现的’ar'(不区分大小写)并且用自己的前缀([b])和后缀([/ b])替换每次出现(即AR,aR和ar).

解决方法

>>> import re
>>> source_str = 'You ARe probably familiaR with wildcard'
>>> re.sub(r"(ar)",r"[b]1[/b]",source_str,flags=re.IGNORECASE)
'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读