Home:ALL Converter>Replace character in a string conditional on appearance of another character in the string Python

Replace character in a string conditional on appearance of another character in the string Python

Ask Time:2012-04-19T01:40:18         Author:hardikudeshi

Json Formatter

I have a string in my code (which consists entirely of lower-case alphabets). I need to replace a character conditional on the appearance of another character after the character I intend to replace in the same string. For example if the character to be replaced is "e" and the conditional character is "t", then we will replace "e" in "forest" but not in "jungle" Is there is way to do this in a simple manner in Python? Thanks for taking out time for this problem.

P.S Please note that there is no repetition of alphabets in the characters I am working with.

Author:hardikudeshi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10214872/replace-character-in-a-string-conditional-on-appearance-of-another-character-in
Andrew Clark :

If you want to replace all occurrences of e that have a t after them, you can use the following:\n\n>>> import re\n>>> re.sub(r'e(?=.*t)', 'i', 'forest')\n'forist'\n>>> re.sub(r'e(?=.*t)', 'i', 'jungle')\n'jungle'\n>>> re.sub(r'e(?=.*t)', 'i', 'greet')\n'griit'\n\n\nThis uses a lookahead, which is a zero-width assertion that checks to see if t is anywhere later in the string without consuming any characters. This allows the regex to find each e that fits this condition instead of just the first one.",
2012-04-18T17:51:22
Danica :

>>> import re\n>>> re.sub(r'e(.*t)', r'i\\1', \"forest\")\n'forist'\n>>> re.sub(r'e(.*t)', r'i\\1', \"jungle\")\n'jungle'\n",
2012-04-18T17:42:59
Abhijit :

What's wrong with?\n\nif st.find(\"e\") < st.find(\"t\"): \n st.replace(\"e\",\"i\",1)\n\n\nand its readable\n\nIf the occurrence is not unique you can also do\n\n>>> pos_t=st.find(\"t\")\n>>> \"\".join(e if (e != 'e' or i > pos_t) else 'i' for i,e in enumerate(st))\n",
2012-04-18T17:51:11
Akavall :

This will replace all 'e's with 'i's if the part that comes before the last t: \n\ndef sub(x): \n return x[:x.rfind('t')].replace('e','t') + x[x.rfind('t'):]\n\n\nResult:\n\n>>> sub('feeoeresterette')\n'fttotrtsttrttte'\n>>> sub('forest')\n'fortst'\n>>> sub('greet')\n'grttt'\n>>> sub('theater')\n'thtater''\n",
2012-04-18T18:03:20
yy