用另一个列表中的字符串的一部分填充列表,直到我到达一个数字

时间:2018-10-11 04:09:17

标签: python python-3.x

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)

4 个答案:

答案 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]