- python - 去除字元外的字元串部分

目標是遍歷字元串列表,對於列表的每個索引,刪除外部格式,如下所示:

例如,這是給定的列表:


st1 = ['apple', 'none:apple_one', 'two:apple_two:word', 'banana', 'there:banana_one:ban', 'there:bana']



我想讓腳本將列表轉換為以下格式:


output = ['apple', 'apple_one', 'apple_two', 'banana', 'banana_one', 'there']



請注意,:之外的單詞都被刪除,例如'two:apple_two:word' -> 'apple_two'

我已經嘗試在split(':')函數中使用for loop,然後對轉換為list,的每個字元串的[1]元素按順序索引sub,但這不適合我,


for j in st1:


 print(j)


 k = 0


 if ':' in j:


 st1[k] = j.split(':')[1]


 k += 1



 print(st1[k])



output = 'n'.join(st1)



返回的結果:


apple


none:apple_one


none:apple_one


none:apple_one


two:apple_two:word


none:apple_one


banana


none:apple_one


there:banana_one:ban


none:apple_one


there:bana


none:apple_one



时间:

試試這個:


st1 = ['apple', 'none:apple_one', 'two:apple_two:word', 'banana', 'there:banana_one:ban', 'there:bana']



for i, val in enumerate(st1):


 if ':' in val:


 st1[i] = val.split(':')[1]



output = 'n'.join(st1)



print(output)



輸出:


apple


apple_one


apple_two


banana


banana_one


bana



當前代碼的問題在於,每次循環運行時,你總是將k重置為0.這意味著你只能對(或索引0 )中的第一個st1項進行操作

一行版本:


'n'.join(x.split(":")[1] if":" in x else x for x in st1)



或者,你也可以使用re


import re



st1 = ['apple', 'none:apple_one', 'two:apple_two:word', 'banana', 'there:banana_one:ban', 'there:bana']



st2=list(map(lambda x: re.sub(r"(^[^:]*:)|(:[^:]*$)","", x), st1))



輸出:


['apple', 'apple_one', 'apple_two', 'banana', 'banana_one', 'bana']




>>> [split[1 if len(split) > 1 else 0] for string in st1 if (split := string.split(':',2))]


['apple', 'apple_one', 'apple_two', 'banana', 'banana_one', 'bana']



...