Nick M. Nick M. - 1 year ago 61
Python Question

How to replace only a certain part of a list?

How do I replace apple in the beginning of each string in the list to orange?

Here is what I have tried:

appleList = ['apple_00', 'apple_01', 'apple_02', 'apple_03']

appleList = ['orange' if 'apple' in appleList]

print appleList

['apple_00', 'apple_01', 'apple_02', 'apple_03']

Desired Output:
['orange_00', 'orange_01', 'orange_02', 'orange_03']

Answer Source

You should use the replace method to modify the strings inside the list:

>>> my_list = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
>>> print([s.replace('Apple', 'Orange') for s in my_list])

this will print

['Orange_00', 'Orange_01', 'Orange_02', 'Orange_03']

As a side note, you should really use lowercase names for variables per Python Style Guide - PEP08.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download