I have a list of like below, some of them are prefixed with "abc_" and some of them are not.
What would be the effective way to prefix the ones that do not have the prefix?
(Basically, I need all of them to have the prefix "abc_")
my_list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
Required output:
my_list = ['abc_apple','abc_orange','abc_cherry','abc_berry','abc_banana']
Is it Possible to do it using list comprehension?
Don't name lists with a Python Keyword. list
is a keyword in Python. You can use list comprehension to do it using .startswith()
:
list1 = ['abc_apple','abc_orange','cherry','abc_berry','banana']
list1 = ['abc_'+i if not i.startswith('abc_') else i for i in list1]
print(list1)
Output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']