Python中从右到左的字符串替换? [英] Right-to-left string replace in Python?

查看:48
本文介绍了Python中从右到左的字符串替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 中进行字符串替换,但只执行从右到左的第一个实例.在理想的世界中,我会:

myStr = "密西西比"打印 myStr.rreplace("iss","XXX",1)>小姐XXXippi

鉴于 rreplace 不存在,这样做的最佳方法是什么?

解决方案

rsplitjoin 可用于模拟 rreplace 的效果>

<预><代码>>>>'XXX'.join('密西西比'.rsplit('iss', 1))'小姐XXXippi'

I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I'd have:

myStr = "mississippi"
print myStr.rreplace("iss","XXX",1)

> missXXXippi

What's the best way of doing this, given that rreplace doesn't exist?

解决方案

rsplit and join could be used to simulate the effects of an rreplace

>>> 'XXX'.join('mississippi'.rsplit('iss', 1))
'missXXXippi'

这篇关于Python中从右到左的字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆