的Python:替换字符串中的条款除了最后(Python: replace terms in a s

2019-09-01 08:13发布

如何去约在字符串替换方面 - 除了最后,需要进行更换,以不同的东西?

一个例子:

    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'。 我已经通过计算器和蟒蛇教程搜查,但找不到一个功能只需更换最后发现来看,任何人都可以帮忙吗?

Answer 1:

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.


Answer 2:

In [1]: letters = 'a;b;c;d'

In [2]: ' & '.join(letters.replace(';', ', ').rsplit(', ', 1))
Out[2]: 'a, b, c & d'


Answer 3:

在一行中做不知道发生次数的另一种方式:

letters = 'a;b;c;d'
letters[::-1].replace(';', ' & ', 1)[::-1].replace(';', ', ')


文章来源: Python: replace terms in a string except for the last