Home > OS >  Remove underscore from a list: Python
Remove underscore from a list: Python

Time:08-13

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

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?

CodePudding user response:

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]

CodePudding user response:

Or if you absolutely must/want to stick to regex:

import re
my_list = ['aaa', 'bb_bb', 'cc', 2]
my_list= [re.sub('_', '', value) if isinstance(value, str) else value for value in my_list]
print(my_list)

Result:

['aaa', 'bbbb', 'cc', 2]
  • Related