Search code examples
pythonstringlistsplitstring-formatting

How to strip certain characters from a string in python


I am trying to strip certain characters from a string. The string I have is -

test_list = ['INFO:      196ns ### Starting ABC Test ###\n', 'INFO:     310ns ### Starting write_def_test ###\n', 'INFO:     752ns ### Starting write_55s_test ###\n', 'INFO:    152ns ### Starting rands_test ###\n', 'INFO:    237ns ### Starting dog_wffs_test ###\n']

The code I have is -

test_list_1 = []
for i in test_list:
    m = i.strip("INFO:      ")
    m = m.strip("###")
    test_list_1.append(m)
print(test_list_1)

The output I am looking for is -

['ABC Test', 'write_def_test', 'write_55s_test', 'rands_test', 'dog_wffs_test']

How can I get it?


Solution

  • You're better off using regex here, i.e.:

    import re
    
    out = re.findall('Starting ([^#]+)', '|'.join(test_list))