Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: replace terms in a string except for the last

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?

like image 388
user2330075 Avatar asked Apr 28 '13 21:04

user2330075


People also ask

How do you replace part of a string in Python?

replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do I remove the last occurrence of a string in Python?

Using rfind() function For that, use the rfind() function of the string class. It returns the highest index of the substring in the string i.e., the index position of the last occurrence of the substring. Then using the subscript operator and index range, replace that last occurrence of substring.

What is .replace in Python?

The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring. Replace() returns a new string in which old substring is replaced with the new substring.

How do you remove the first and last words in Python?

Method #1: Using split() Method This task can be performed using the split function which performs a split of words and separates the first word of string with the entire words.


1 Answers

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.
like image 168
Ashwini Chaudhary Avatar answered Sep 25 '22 12:09

Ashwini Chaudhary