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

2024-09-28 13:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

比如说,

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

例外输出:['apple','red','D30','green']

谢谢


Tags: 字符串apple数字greenredd30
3条回答

这应该起作用:

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

这将删除一个下划线,后跟字符串末尾的数字

相关问题 更多 >

    热门问题