use*_*075 8 python string replace
如何替换字符串中的术语 - 除了最后一个,需要替换为不同的东西?
一个例子:
letters = 'a;b;c;d'
Run Code Online (Sandbox Code Playgroud)
需要改为
letters = 'a, b, c & d'
Run Code Online (Sandbox Code Playgroud)
我使用了replace函数,如下所示:
letters = letters.replace(';',', ')
Run Code Online (Sandbox Code Playgroud)
给
letters = 'a, b, c, d'
Run Code Online (Sandbox Code Playgroud)
问题是我不知道如何将最后一个逗号替换为&符号.不能使用位置相关函数,因为可以存在任何数量的字母,例如'a; b'或'a; b; c; d; e; f; g'.我已经搜索了stackoverflow和python教程,但找不到一个函数来替换最后找到的术语,有人可以帮忙吗?
在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'
Run Code Online (Sandbox Code Playgroud)
帮助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.
Run Code Online (Sandbox Code Playgroud)