'Python List : add Prefix if it is not Prefixed
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?
Solution 1:[1]
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']
Solution 2:[2]
Just following if/else in a list comprehension you could do something like this:
my_list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
my_list = [f"abc_{word}" if not word.startswith("abc_") else word for word in my_list]
print(my_list)
Output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
Solution 3:[3]
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if 'abc_' in list[i]:
pass
else:
list[i] = 'abc_' + list[i]
list
output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
OR
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if 'abc_' not in list[i]:
list[i] = 'abc_' + list[i]
list
OR Better answer
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if list[i].startswith('abc_'):
pass
else:
list[i] = 'abc_' + list[i]
list
Solution 4:[4]
Try method map to make an iterator that computes the function using arguments from each of the iterables.
>>> lst = ['abc_apple','abc_orange','cherry','abc_berry','banana']
>>> result = list(map(lambda x:x if x.startswith('abc_') else 'abc_'+x, lst))
>>>
>>> result
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhyuday Vaish |
| Solution 2 | Tzane |
| Solution 3 | |
| Solution 4 | Jason Yang |
