a = ["Its_My_Life_3:44","Say_It_Isn't_So_3:33","Thank_You_for_Loving_Me_5:09"]b = []我想b看起来像这样b = ["Its My Life","Say It Isn't So","Thank You for Loving Me"]这是我正在努力使用的代码,我正在努力寻找一个只会附加歌曲名称、替换_为" "而不包含数字的条件。我知道我可以用格式做一些事情并替换,但我无法弄清楚。for song in a: b.append(song[0:8)]) # print(b)
3 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
怎么样:
代码:
b = [' '.join(x.split('_')[:-1]) for x in a]
如何?
这将拆分 上的字符串_
,丢弃最后一个字段,然后使用空格重新连接。
测试代码:
a = ["Its_My_Life_3:44","Say_It_Isn't_So_3:33","Thank_You_for_Loving_Me_5:09"] print([' '.join(x.split('_')[:-1]) for x in a]
结果:
['Its My Life', "Say It Isn't So", 'Thank You for Loving Me']
ITMISS
TA贡献1871条经验 获得超8个赞
使用str.replace()和r.partition()和列表理解
a = [i.replace('_', ' ') for i in a]
b = [i.rpartition(' ')[0] for i in a]
展开
b = []
for i in a:
i = i.rpartition(' ')
b.append(i[0])
单列表理解:
b = [(i.replace('_', ' ')).rpartition(' ')[0] for i in a]
添加回答
举报
0/150
提交
取消