2

I have a list in python.

MyList = ["ONE APPLE", "TWO PEAR", "THREE APPLE"]

I want to replace all the 'E' characters with 'A' characters in the fruit words, but not in the number words. So far I have tried using list.replace, however as far as I can tell indiscriminately replaces all 'E's with 'A's.

The code list = [list.replace('E', 'A') for list in list] outputs

"ONA APPLA"
"TWO PAAR"
"THRAA APPLA" 

Whereas I want the following.

"ONE APPLA"
"TWO PAAR"
"THREE APPLA" 

Is there any way of using the replace function after the ' ', or is another method more appropriate?

1 Answer 1

1
>>> my_list = ["ONE APPLE", "TWO PEAR", "THREE APPLE"]
>>> result = [ ''.join(i.split()[0] + ' '+ i.rsplit()[1].replace('E', 'A')) for i in my_list ]
>>> result
['ONE APPLA', 'TWO PAAR', 'THREE APPLA']

#OR

>>> result = [ '{} {}'.format(i.split()[0], i.rsplit()[1].replace('E', 'A')) for i in my_list ]
>>> result
['ONE APPLA', 'TWO PAAR', 'THREE APPLA']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for quick response. An ideal solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.