前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >python替换第n个字符串_替换字符串中第n个出现的子字符串

python替换第n个字符串_替换字符串中第n个出现的子字符串

作者头像
用户7886150
修改2021-01-11 10:17:51
修改2021-01-11 10:17:51
4.8K0
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Python中的replace替换子字符串

我已经想出了下面的方法,它还考虑了替换所有出现在左边或右边的“旧”字符串的选项。当然,由于标准str.replace工作得很好,因此没有替换所有引用的选项。def nth_replace(string, old, new, n=1, option='only nth'):

 """

 This function replaces occurrences of string 'old' with string 'new'.

 There are three types of replacement of string 'old':

 1) 'only nth' replaces only nth occurrence (default).

 2) 'all left' replaces nth occurrence and all occurrences to the left.

 3) 'all right' replaces nth occurrence and all occurrences to the right.

 """

 if option == 'only nth':

 left_join = old

 right_join = old

 elif option == 'all left':

 left_join = new

 right_join = old

 elif option == 'all right':

 left_join = old

 right_join = new

 else:

 print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")

 return None

 groups = string.split(old)

 nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]

 return new.join(nth_split)

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档