简体   繁体   中英

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

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.

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

If you want to replace all occurrences of e that have a t after them, you can use the following:

>>> import re
>>> re.sub(r'e(?=.*t)', 'i', 'forest')
'forist'
>>> re.sub(r'e(?=.*t)', 'i', 'jungle')
'jungle'
>>> re.sub(r'e(?=.*t)', 'i', 'greet')
'griit'

This 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.

>>> import re
>>> re.sub(r'e(.*t)', r'i\1', "forest")
'forist'
>>> re.sub(r'e(.*t)', r'i\1', "jungle")
'jungle'

What's wrong with?

if st.find("e") < st.find("t"): 
    st.replace("e","i",1)

and its readable

If the occurrence is not unique you can also do

>>> pos_t=st.find("t")
>>> "".join(e if (e != 'e' or i > pos_t) else 'i' for i,e in enumerate(st))

This will replace all 'e's with 'i's if the part that comes before the last t:

def sub(x):   
    return x[:x.rfind('t')].replace('e','t') + x[x.rfind('t'):]

Result:

>>> sub('feeoeresterette')
'fttotrtsttrttte'
>>> sub('forest')
'fortst'
>>> sub('greet')
'grttt'
>>> sub('theater')
'thtater''

The following is a function that should do what you want:

>>> def replace(source, replacee, replacement, conditional):
...     if source.find(replacee) < source.rfind(conditional):
...         return source.replace(replacee, replacement)
...     else:
...         return source

Or, if you want it less verbose:

>>> def replace(source, replacee, replacement, conditional):
...     return source.find(replacee) < source.rfind(conditional) and source.replace(replacee, replacement) or source

Both yield should yield the same results, here are some examples:

>>> replace('forest', 'e', 'i', 't')
'forist'
>>> replace('jungle', 'e', 'i', 't')
'jungle'
>>> replace('tales', 'e', 'i', 't')
'tales'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM