0

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])
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Do these values always end in a blank space or there could be more than one word? – Ignatius Reilly Jul 05 '22 at 17:35
  • This should solve your problem: https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean, look in particular for something called _positive lookbehind_ – Ignatius Reilly Jul 05 '22 at 17:38
  • 1
    Does this answer your question? [How to get a string after a specific substring?](https://stackoverflow.com/questions/12572362/how-to-get-a-string-after-a-specific-substring). Do this for each element of `new` – Pranav Hosangadi Jul 05 '22 at 18:01

1 Answers1

-1
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]
koegl
  • 505
  • 2
  • 13