Python:替换字符串中除最后一个之外的术语 [英] Python: replace terms in a string except for the last

查看:38
本文介绍了Python:替换字符串中除最后一个之外的术语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何替换字符串中的术语 - 除了最后一个,需要替换为不同的内容?

How does one go about replacing terms in a string - except for the last, which needs to be replaced to something different?

示例:

    letters = 'a;b;c;d'

需要改成

    letters = 'a, b, c & d'

我已经使用了替换功能,如下:

I have used the replace function, as below:

    letters = letters.replace(';',', ')

给予

    letters = 'a, b, c, d'

问题是我不知道如何将最后一个逗号替换为&符号.不能使用位置相关函数,因为可能有任意数量的字母,例如 'a;b' 或 'a;b;c;d;e;f;g' .我已经搜索过 stackoverflow 和 python 教程,但找不到一个函数来替换最后找到的术语,有人可以帮忙吗?

The problem is that I do not know how to replace the last comma from this into an ampersand. A position dependent function cannot be used as there could be any number of letters e.g 'a;b' or 'a;b;c;d;e;f;g' . I have searched through stackoverflow and the python tutorials, but cannot find a function to just replace the last found term, can anyone help?

推荐答案

str.replace 中,您还可以传递一个可选的第三个参数(count),用于处理正在完成的替换次数.

In str.replace you can also pass an optional 3rd argument(count) which is used to handle the number of replacements being done.

In [20]: strs = 'a;b;c;d'

In [21]: count = strs.count(";") - 1

In [22]: strs = strs.replace(';', ', ', count).replace(';', ' & ')

In [24]: strs
Out[24]: 'a, b, c & d'

str.replace 的帮助:

S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring
old replaced by new.  If the optional argument count is
given, only the first count occurrences are replaced.

这篇关于Python:替换字符串中除最后一个之外的术语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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