简体   繁体   中英

How can I access a certain length after character in list

I am reading in a text file and I want to access the information after a certain delimiter for example I'll have ["-t2=zoe", "-d2= box"] as a list and I want the values zoe and box .

def Unlock(file):
 
    inp = input("1: Command Line or 2: Log File ")
    if inp == "1":
        print("You chose cmd line")
        with open(file) as f:
            lines = f.readlines()
            new = ""
            if(len(lines) == 1):
                new = lines[0]
                new = new.replace('-t', '!-t')
                new = new.split('!')
                
            else:
                new = lines
        for i in range(1,len(new)):
            
            if '-t' in new[i]:   
                print(new[i])
example = ["-t2=zoe", "-d2=box"]

With a standard for loop you can just loop over all the elements, split at = and append the right side (index 1) to a new list. By using the split() function you will get an array with two elements - the first element contains all the characters before the chosen split character and the second the characters after the split character. If there are no characters before or after, the respective element in the list will be empty ( '' )

result = []
for element in example:
    result.append(element.split("=")[1])

Or you can use a list comprehension to do this in one line:

result_list_comprehension = [element.split("=")[1] for element in example]

Or if you don't want to split at a specific character, but just at a specific index (in this case index 4 ):

result_list_comprehension_fixed_length = [element[4:] for element in example]

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