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

Remove underscore from a list: Python

Let’s say I have the following list:

my_list = ['aaa', 'bb_bb', 'cc', 2]

I would like to remove underscore _ from a list element and would like to get

my_list = ['aaa', 'bbbb', 'cc', 2]

I tried this

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= [re.sub('_', '', _) for _ in my_list ]

For some reason I am getting an error TypeError: expected string or bytes-like object.

Can anyone help with this?

>Solution :

It’s because one of the elements is neither string nor bytes.

Also, you do not need re.sub to replace all instances of a character in a string, use str.replace instead, plus using _ as a variable name usually means it is ignored.

Try this instead:

[v.replace('_', '') if isinstance(v, str) else v for v in my_list]
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