2024-09-28 13:26:09 发布
网友
如何使用Python删除字符串中带有“u”的部分和连接在一起的数字
比如说,
输入:['apple_3428','red_458','D30','green']
['apple_3428','red_458','D30','green']
例外输出:['apple','red','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']
new_list
['apple', 'red', 'D30', 'green']
基本上,您分割my_list的每个元素(应该是字符串),然后取第一个元素,即_之前的部分。如果_不存在,则不会拆分字符串
my_list
_
试试这个:
output_list = [x.split('_')[0] for x in input_list]
将正则表达式与re.sub一起使用:
re.sub
import re [re.sub("_\d+$", "", x) for x in ['apple_3428','red_458','D30','green']] # ['apple_3428','red_458','D30','green']
这将删除一个下划线,后跟字符串末尾的数字
这应该起作用:
new_list
将是['apple', 'red', 'D30', 'green']
基本上,您分割
my_list
的每个元素(应该是字符串),然后取第一个元素,即_
之前的部分。如果_
不存在,则不会拆分字符串试试这个:
将正则表达式与
re.sub
一起使用:这将删除一个下划线,后跟字符串末尾的数字
相关问题 更多 >
编程相关推荐