Extracting part of a string with irregular delimiters in python
Question: I am wanting to extract the last part of the name of the file that is
delimited by a constant prefix and '.csv'

Name of the file might look like:

> constant_prefix_**my file name**.csv

or

> constant_prefix_**myfilename**.csv

I would like to extract the values marked in bold into a variable.

Please advise.


Answer: Script:

    
    
    import re
    
    name1 = 'constant_prefix_my file name.csv'
    name2 = 'constant_prefix_myfilename.csv'
    
    def get_name(string):
        return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
    

Demo:

    
    
    print get_name(name1)
    print get_name(name2)
    

Output:

    
    
    my file name
    myfilename
    

Or you can do this:

    
    
    names = [get_name(n) for n in [name1, name2]]
    print names
    

Output:

    
    
    ['my file name', 'myfilename']
    

