删除字符串中字符和数字连接在一起的部分

Remove the part with a character and numbers connected together in a string

如何使用Python删除字符串中“_”和数字连接在一起的部分?

例如,

输入:['apple_3428','red_458','D30','green']

异常输出:['apple','red','D30','green']

谢谢!

这应该有效:

my_list = ['apple_3428','red_458','D30','green']
new_list = []
for el in my_list:
    new_list.append(el.split('_')[0])

new_list 将是 ['apple', 'red', 'D30', 'green']

基本上你拆分了 my_list 的每个元素(应该是字符串)然后你拿第一个,即 _ 之前的部分。如果 _ 不存在,则不会拆分字符串。

试试这个:

output_list = [x.split('_')[0] for x in input_list]

使用正则表达式 re.sub:

import re

[re.sub("_\d+$", "", x) for x in ['apple_3428','red_458','D30','green']]
# ['apple_3428','red_458','D30','green']

这将从字符串末尾去除下划线后跟数字。

input_list = ['apple_3428','red_458','D30','green']
output_list = []

for i in input_list:
    output_list.append(i.split('_', 1)[0])

您可以简单地拆分字符串。

我不确定需要哪个,所以提供几个选项

另外 list comp 比 map + lambda 更好,而且 list comp 更像 pythonic,List comprehension vs map

  1. \d+代表至少一位数字
  2. \d* 代表 >= 0 位
>>> 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']