【问题标题】:Python: replace terms in a string except for the lastPython:替换字符串中的术语,除了最后一个
【发布时间】:2013-04-22 11:46:12
【问题描述】:
如何替换字符串中的术语 - 除了最后一个,它需要替换为不同的东西?
一个例子:
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 教程,但找不到一个函数来替换最后找到的术语,有人可以帮忙吗?
【问题讨论】:
标签:
python
string
replace
【解决方案1】:
letters = 'a;b;c;d'
lettersOut = ' & '.join(letters.replace(';', ', ').rsplit(', ', 1))
print(lettersOut)
【解决方案2】:
在str.replace 中,您还可以传递一个可选的第三个参数(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.
【解决方案3】:
在不知道出现次数的情况下在一行中执行此操作的另一种方法:
letters = 'a;b;c;d'
letters[::-1].replace(';', ' & ', 1)[::-1].replace(';', ', ')