Home > Software design >  Python - Test if string is before another string
Python - Test if string is before another string

Time:01-15

File contents:

abc 
Swan
abc2
Swan
abc3

... How would test to see if "Swan" exists, but only before "abc2" (in Python)

(First post, so pls excuse a bit of ignorance

CodePudding user response:

One can use this:

txt = '''
abc 
Swan
abc2
Swan
abc3
'''

import re

if re.search(r'Swan\nabc2', txt, re.M):
    print('True')

This will look if there is somewhere in the text Swan and somewhere (not direct) behind it there should be abc2.

If you are looking per line one can loop over the lines:

lst_txt = txt.split('\n')
for line, lineafter in zip(lst_txt[:-1], lst_txt[1:]):
    if line == 'Swan' and lineafter == 'abc2':
        print('True')

CodePudding user response:

if you have the data from the file as a string, you can split it into lines, if its in lines, then just convert it to a list of all lines. You can then use list.index() to find what line the value appears on and compare it to other values like so:

testStr = """abc 
Swan
abc2
Swan
abc3"""

lines = testStr.splitlines()

print(lines.index('Swan'))
print(lines.index('abc2'))
if lines.index('Swan') < lines.index('abc2'):
    print('Swan comes before abc2')

Which outputs:

1
2
Swan comes before abc2

CodePudding user response:

if file is txt file, this can be the way. ex) filename : content.txt

with open('content.txt', 'r') as f:
    r = f.readlines()
    for i, val in enumerate(r):
        word = val.replace('\n', '')
        if val == 'Swan':
            print('Position of Swan :', i)
        elif val == 'abc2':
            print('Position of abc2 :', i)
            break

CodePudding user response:

x_before_y iterates through a iterable (e.g. a list) and returns True as soon as it finds a string x that occurs before the string y.

def x_before_y(x, y, iterable):
    for i, el in enumerate(iterable):
        if el == y and iterable[i-1] == x:
            return True
    return False

lines = ["x", "Swan", "abc2", "x", "Swan"]
x_before_y("Swan", "abc2", lines) #  True
x_before_y("abc2", "Swan", lines) #  False
  •  Tags:  
  • Related