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)
答案 0 :(得分:3)
怎么样?
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']
答案 1 :(得分:1)
一个较小的答案是
import re
for song in a:
b.append(re.match('\D*', song).group().replace('_', ' ').strip())
print(b)
答案 2 :(得分:0)
尝试一下:
for song in a:
b.append(song[:-5].replace("_"," "))
print(b)
答案 3 :(得分:0)
使用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]