14

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

An example:

    letters = 'a;b;c;d'

needs to be changed to

    letters = 'a, b, c & d'

I have used the replace function, as below:

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

to give

    letters = 'a, b, c, d'

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?

user2330075
  • 143
  • 1
  • 4

3 Answers3

17

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'

Help on 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.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4
letters = 'a;b;c;d'
lettersOut = ' & '.join(letters.replace(';', ', ').rsplit(', ', 1))
print(lettersOut)
info-farmer
  • 255
  • 3
  • 18
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
3

Another way of doing it in one line without knowing the number of occurrences:

letters = 'a;b;c;d'
letters[::-1].replace(';', ' & ', 1)[::-1].replace(';', ', ')
Thijs van Dien
  • 6,516
  • 1
  • 29
  • 48