如何替换字符串末尾的某些字符? [英] How to replace the some characters from the end of a string?

查看:45
本文介绍了如何替换字符串末尾的某些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换 python 字符串末尾的字符.我有这个字符串:

I want to replace characters at the end of a python string. I have this string:

 s = "123123"

我想用 x 替换最后一个 2.假设有一个方法叫做replace_last:

I want to replace the last 2 with x. Suppose there is a method called replace_last:

 r = replace_last(s, '2', 'x')
 print r
 1231x3

是否有任何内置或简单的方法可以做到这一点?

Is there any built-in or easy method to do this?

推荐答案

这正是 rpartition 函数的用途:

This is exactly what the rpartition function is used for:

rpartition(...)S.rpartition(sep) -> (head, sep, tail)

rpartition(...) S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it.  If the
separator is not found, return two empty strings and S.

我编写了这个函数,展示了如何在您的用例中使用 rpartition:

I wrote this function showing how to use rpartition in your use case:

def replace_last(source_string, replace_what, replace_with):
    head, _sep, tail = source_string.rpartition(replace_what)
    return head + replace_with + tail

s = "123123"
r = replace_last(s, '2', 'x')
print r

输出:

1231x3

这篇关于如何替换字符串末尾的某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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