简体   繁体   中英

Replace part of the list element

I have a list variable which has elemnts like below: ['Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131121.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131150.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131160.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131169.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131189.csv']

This is file name with file path in it. Want to build a list with only file name, how can i do that? Output should be:

['bounce-20211109-131121.csv', 'bounce-20211109-131150.csv', 'bounce-20211109-131160.csv', 'bounce-20211109-131169.csv', 'bounce-20211109-131189.csv'] ie strip out string 'Cordial/contactactivity/export/bounce/0-ContactActivity-'

You can use os.path.split ( docs here ) and get the last segment. Then you just need to trim the part you don't want.

import os
data = [
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131121.csv', 
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131150.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131160.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131169.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131189.csv'
]
data = [os.path.split(i)[-1].replace('0-ContactActivity-', '') for i in data]

resulting in:

>>> data
['bounce-20211109-131121.csv', 'bounce-20211109-131150.csv', 'bounce-20211109-131160.csv', 'bounce-20211109-131169.csv', 'bounce-20211109-131189.csv']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM