#!/usr/bin/python3 # =================================================================== # this demo replaces sub-strings with other strings, etc. # and display the modified strings # ------------------------------------------------------------------- # 1. remove '_data' from the initial strings # 2. replace '.txt' with '.txt' in the initial strings # 3. convert modified strings to lowwercase # 4. print out the resulting strings # =================================================================== import re # ---- test input data oldstrs = [ 'ABC_data.dat', 'def_DATA.dat', 'ghi_data.dat', 'JKL.DAT', 'xyz.dat', 'oops.xxx' ] # ------------------------------------------------------------------- # return a list of modified strings # ------------------------------------------------------------------- # regexp patterns are raw (r) strings # ------------------------------------------------------------------- # Python Doc: re.sub(pattern,repl,string,count=0,flags=0) # (if no match is found, the input string is returned) # ------------------------------------------------------------------- def create_new_list(oldlst): newlst = [] count = 0 for s in oldlst: # ---- remove '_data' sub-string s1 = re.sub(r'_data','',s,flags=re.IGNORECASE) # ---- replace '.dat' sub-string s2 = re.sub(r'\.dat$','.txt',s1,flags=re.IGNORECASE) ##print('>> {}'.format(s2)) # ---- convert to lowercase s3 = s2.lower() # ---- add new strings to the returned list newlst.append(s3) count += 1 # ---- return list print("{} new strings returned".format(count)) return newlst # ------------------------------------------------------------------- # main # ------------------------------------------------------------------- if __name__ == '__main__': ##print(oldstrs) newstrs = create_new_list(oldstrs) for s in newstrs: print(s)