Home > database >  Python: Index slicing from a list for each index in for loop
Python: Index slicing from a list for each index in for loop

Time:06-01

I got stuck in slicing from a list of data inside a for loop.

list = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']

what I am looking for is to print only key without it values (running/stopped)

Overall code,

for each in list:
    print(each[:]) #not really sure what may work here

result expected:

init.svc.logd

anyone for a quick solution?

CodePudding user response:

If you want print only the key, you could use the split function to take whatever is before : and then replace [ and ] with nothing if you don't want them:

list = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']

for each in list:
    print(each.split(":")[0].replace('[','').replace(']','')) #not really sure what may work here

which gives :

init.svc.logd
init.svc.logd-reinit

CodePudding user response:

You should probably be using a regular expression. The concept of 'key' in the question is ambiguous as there are no data constructs shown that have keys - it's merely a list of strings. So...

import re

list_ = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']

for e in list_:
    if r := re.findall('\[(.*?)\]', e):
        print(r[0])

Output:

init.svc.logd
init.svc.logd-reinit

Note:

This is more robust than string splitting solutions for cases where data are unexpectedly malformed

  • Related