How to remove the part with "_" and numbers connected together in a string using Python?
For example,
Input: ['apple_3428','red_458','D30','green']
Excepted output: ['apple','red','D30','green']
Thanks!
How to remove the part with "_" and numbers connected together in a string using Python?
For example,
Input: ['apple_3428','red_458','D30','green']
Excepted output: ['apple','red','D30','green']
Thanks!
This should work:
my_list = ['apple_3428','red_458','D30','green']
new_list = []
for el in my_list:
new_list.append(el.split('_')[0])
new_list
will be ['apple', 'red', 'D30', 'green']
.
Basically you split every element of my_list
(which are supposed to be strings) and then you take the first, i.e. the part before the _
. If _
is not present, the string will not be split.
Using regular expressions with re.sub
:
import re
[re.sub("_\d+$", "", x) for x in ['apple_3428','red_458','D30','green']]
# ['apple_3428','red_458','D30','green']
This will strip an underscore followed by only digits from the end of a string.
I am not sure which is needed, so present few options
Also list comp is better instead of map + lambda, also list comp is more pythonic, List comprehension vs map
>>> import re
>>> list(map(lambda x: re.sub('_\d+$', '', x), ['green_', 'green_458aaa']))
['green', 'greenaaa']
>>> list(map(lambda x: re.sub('_\d*', '', x), ['green_', 'green_458aaa']))
['green', 'greenaaa']
>>> list(map(lambda x: re.sub('_\d+', '', x), ['green_', 'green_458aaa']))
['green_', 'greenaaa']
>>> list(map(lambda x: x.split('_', 1)[0], ['green_', 'green_458aaa']))
['green', 'green']
input_list = ['apple_3428','red_458','D30','green']
output_list = []
for i in input_list:
output_list.append(i.split('_', 1)[0])
You can simply split the string.