Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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_")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading