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?
>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]