Python:替换字符串中的术语(最后一个除外)
如何替换字符串中的术语-除了最后一个需要替换为其他内容的字符串以外?
一个例子:
letters = 'a;b;c;d'
需要更改为
letters = 'a, b, c & d'
我已经使用了替换功能,如下所示:
letters = letters.replace(';',', ')
给
letters = 'a, b, c, d'
问题是我不知道如何将最后一个逗号替换为“&”号。不能使用与位置相关的函数,因为可以有任意数量的字母,例如’a; b’或’a; b; c; d; e; f;
g’。我已经搜索了stackoverflow和python教程,但找不到能代替最后找到的术语的函数,有人可以帮忙吗?
-
在其中,
str.replace
您还可以传递一个可选的3rd参数(count
),该参数用于处理已完成的替换次数。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.